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

Bun 1.2 Off-Heap FFI Memory Lifecycle and Pointer Pinning Guardrail

Enforces deterministic lifecycle management, explicit pointer pinning, and strict ownership boundaries for off-heap memory across the JavaScriptCore-to-Rust native bridge via bun:ffi. Eliminates use-after-free, memory corruption, and double-free hazards caused by JavaScriptCore garbage collection sweeping memory backing buffers while active native threads hold raw pointers.

Prohibited Anti-Pattern: Passing Ephemeral JSC Buffers or Naked Pointers to Asynchronous Native FFI Without Explicit Lifetime Pinning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Off-Heap FFI Memory Lifecycle and Pointer Pinning Guardrail - Enforces deterministic lifecycle management, explicit pointer pinning, and strict ownership boundaries for off-heap memory across the JavaScriptCore-to-Rust native bridge via bun:ffi. Eliminates use-after-free, memory corruption, and double-free hazards caused by JavaScriptCore garbage collection sweeping memory backing buffers while active native threads hold raw pointers.
globs: src/**/*.{ts,tsx}, native/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-off-heap-lifecycle-invariants"
---

# Bun 1.2 Off-Heap FFI Memory Lifecycle and Pointer Pinning Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing Ephemeral JSC Buffers or Naked Pointers to Asynchronous Native FFI Without Explicit Lifetime Pinning

## System Constraints
You are a Principal Software Architect enforcing zero-trust off-heap memory invariants in Bun 1.2 `bun:ffi` native integrations. JavaScriptCore's garbage collector is unaware of native Rust allocations and asynchronous thread executions; therefore, implicit garbage collection MUST NEVER be trusted with off-heap lifetimes. Every foreign pointer crossing the FFI boundary must adhere to strict RAII disposal, explicit rooting/pinning, and bidirectional allocation symmetry.

## Strict Guidelines
- Engineers MUST ALWAYS enforce allocation symmetry: memory allocated in Rust (`Box::into_raw`) must be freed by a corresponding Rust FFI export (`Box::from_raw`), NEVER by JavaScript runtime engines.
- Engineers MUST ALWAYS pin underlying JavaScript buffers using explicit RAII wrappers implementing TypeScript 5.2+ `Symbol.dispose` or `Symbol.asyncDispose` to ensure pointers outlive native asynchronous workloads.
- Engineers MUST NOT rely on JavaScriptCore `FinalizationRegistry` for deterministic memory freeing, as GC execution is non-deterministic and leads to off-heap memory exhaustion under high throughput.
- Code MUST explicitly validate pointer nullity and boundary bounds (`ptr === 0n || ptr === null`) before dispatching any call to foreign symbols.
- Services MUST ensure that views created via `toArrayBuffer(ptr, byteOffset, byteLength)` are treated as ephemeral borrow views and invalidated immediately upon the native resource disposal.
- Components NEVER pass direct pointers from transient typed arrays (e.g., `ptr(new Uint8Array(...))`) to native functions that execute asynchronously or retain the pointer beyond the call stack.

## Bad vs Good Implementations
### Naive Ephemeral Buffer FFI Dispatch (Use-After-Free Hazard)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: `tempBuffer` is allocated inside the JSC nursery heap. If an asynchronous native Rust thread retains `rawPtr`, Bun's garbage collector can collect or relocate `tempBuffer` as soon as `processData` returns, causing memory corruption or segmentation faults when Rust dereferences the pointer.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

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

export function processData(data: Uint8Array): void {
  // VULNERABILITY: JSC GC can collect or compact `tempBuffer` during async native execution
  const tempBuffer = new Uint8Array(data);
  const rawPtr = ptr(tempBuffer);
  
  lib.symbols.process_async(rawPtr, BigInt(tempBuffer.byteLength));
  // Non-deterministic cleanup or premature drop causes immediate UAF in Rust worker thread
}
```

#### Production Standard (Correct)
> **Standard**: Memory is allocated off-heap directly by Rust, ensuring JavaScriptCore cannot relocate or collect it. Ownership is governed deterministically through TypeScript 5.2 `using` declaration and `Symbol.dispose`, ensuring identical allocation/deallocation symmetry without relying on GC.
```typescript
import { dlopen, FFIType, ptr, toArrayBuffer } from "bun:ffi";

interface NativeLibrary {
  allocate_native_buffer: (size: bigint) => bigint;
  process_async_blocking: (ptr: bigint, size: bigint) => void;
  free_native_buffer: (ptr: bigint, size: bigint) => void;
}

const lib = dlopen("libnative.so", {
  allocate_native_buffer: { args: [FFIType.u64], returns: [FFIType.ptr] },
  process_async_blocking: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.void },
  free_native_buffer: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.void },
}).symbols as unknown as NativeLibrary;

export class PinnedNativeBuffer implements Disposable {
  readonly rawPtr: bigint;
  readonly byteLength: bigint;
  private disposed = false;

  constructor(size: number) {
    this.byteLength = BigInt(size);
    this.rawPtr = lib.allocate_native_buffer(this.byteLength);
    if (this.rawPtr === 0n) {
      throw new Error("Native allocation failed: Out of memory");
    }
  }

  get buffer(): ArrayBuffer {
    if (this.disposed) throw new Error("Access violation: PinnedNativeBuffer already disposed");
    return toArrayBuffer(Number(this.rawPtr), 0, Number(this.byteLength));
  }

  [Symbol.dispose](): void {
    if (!this.disposed) {
      this.disposed = true;
      lib.free_native_buffer(this.rawPtr, this.byteLength);
    }
  }
}

export function executeSafeProcessing(data: Uint8Array): void {
  using pinned = new PinnedNativeBuffer(data.byteLength);
  new Uint8Array(pinned.buffer).set(data);
  
  // Rust owns and processes safely; buffer is pinned and out of reach of JSC GC
  lib.process_async_blocking(pinned.rawPtr, pinned.byteLength);
  // Deterministically freed by Rust deallocator at block exit via Symbol.dispose
}
```

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 Off-Heap FFI Memory Lifecycle and Pointer Pinning Guardrail

Bun 1.2 Off-Heap FFI Memory Lifecycle and Pointer Pinning Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic lifecycle management, explicit pointer pinning, and strict ownership boundaries for off-heap memory across the JavaScriptCore-to-Rust native bridge via bun:ffi. Eliminates use-after-free, memory corruption, and double-free hazards caused by JavaScriptCore garbage collection sweeping memory backing buffers while active native threads hold raw pointers. 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 Ephemeral JSC Buffers or Naked Pointers to Asynchronous Native FFI Without Explicit Lifetime Pinning 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 Ephemeral JSC Buffers or Naked Pointers to Asynchronous Native FFI Without Explicit Lifetime PinningCritical
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 enforce allocation symmetry

Engineers MUST ALWAYS enforce allocation symmetry: memory allocated in Rust (`Box::into_raw`) must be freed by a corresponding Rust FFI export (`Box::from_raw`), NEVER by JavaScript runtime engines.

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 pin underlying JavaScript buffers using explicit RAII wrappers implementing TypeScript 5.2+ `Symbol.dispose` or `Symbol.asyncDispose` to ensure pointers outlive native asynchronous workloads.

Engineers MUST ALWAYS pin underlying JavaScript buffers using explicit RAII wrappers implementing TypeScript 5.2+ `Symbol.dispose` or `Symbol.asyncDispose` to ensure pointers outlive native asynchronous workloads.

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 deterministic memory freeing, as GC execution is non-deterministic and leads to off-heap memory exhaustion under high throughput.

Engineers MUST NOT rely on JavaScriptCore `FinalizationRegistry` for deterministic memory freeing, as GC execution is non-deterministic and leads to off-heap memory exhaustion under high throughput.

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 explicitly validate pointer nullity and boundary bounds (`ptr === 0n || ptr === null`) before dispatching any call to foreign symbols.

Code MUST explicitly validate pointer nullity and boundary bounds (`ptr === 0n || ptr === null`) before dispatching any call to foreign symbols.

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 views created via `toArrayBuffer(ptr, byteOffset, byteLength)` are treated as ephemeral borrow views and invalidated immediately upon the native resource disposal.

Services MUST ensure that views created via `toArrayBuffer(ptr, byteOffset, byteLength)` are treated as ephemeral borrow views and invalidated immediately upon the native resource disposal.

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 pass direct pointers from transient typed arrays (e.g., `ptr(new Uint8Array(...))`) to native functions that execute asynchronously or retain the pointer beyond the call stack.

Components NEVER pass direct pointers from transient typed arrays (e.g., `ptr(new Uint8Array(...))`) to native functions that execute asynchronously or retain the pointer beyond the call stack.

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 Off-Heap FFI Memory Lifecycle and Pointer Pinning Guardrail critical for AI coding assistants?

Enforces deterministic lifecycle management, explicit pointer pinning, and strict ownership boundaries for off-heap memory across the JavaScriptCore-to-Rust native bridge via bun:ffi. Eliminates use-after-free, memory corruption, and double-free hazards caused by JavaScriptCore garbage collection sweeping memory backing buffers while active native threads hold raw pointers. 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 Ephemeral JSC Buffers or Naked Pointers to Asynchronous Native FFI Without Explicit Lifetime Pinning) 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