This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-ffi-memory-pinning-gc-lifespan

Bun 1.2 Native FFI Heap Pointer Pinning and GC Lifespan Management

Enforces strict heap memory pinning and explicit reference anchoring during zero-copy asynchronous native FFI invocations in Bun 1.2. JavaScriptCore's garbage collector will eagerly collect unreferenced TypedArrays, reallocating or zeroing underlying memory pages while native C/Rust worker threads read or write to raw pointers, leading to catastrophic memory corruption and segmentation faults.

Prohibited Anti-Pattern: Ephemeral TypedArray Zero-Copy Transfer to Background Native Threads Causing Use-After-Free

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native FFI Heap Pointer Pinning and GC Lifespan Management - Enforces strict heap memory pinning and explicit reference anchoring during zero-copy asynchronous native FFI invocations in Bun 1.2. JavaScriptCore's garbage collector will eagerly collect unreferenced TypedArrays, reallocating or zeroing underlying memory pages while native C/Rust worker threads read or write to raw pointers, leading to catastrophic memory corruption and segmentation faults.
globs: src/**/*.{ts,js,mts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-memory-pinning-gc-lifespan"
---

# Bun 1.2 Native FFI Heap Pointer Pinning and GC Lifespan Management

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ephemeral TypedArray Zero-Copy Transfer to Background Native Threads Causing Use-After-Free

## System Constraints
You are a Principal Systems Architect enforcing absolute memory safety and pointer pinning invariants for Bun 1.2 Native FFI bindings. You must prevent premature garbage collection of JavaScriptCore memory buffers passed into asynchronous or non-blocking C/Rust native dynamic libraries. Mandate explicit root referencing, finalizer coordination, and deterministic buffer release patterns.

## Strict Guidelines
- Engineers MUST ALWAYS anchor TypedArray and Buffer references in a long-lived JavaScript scope, registry, or Map until the native asynchronous FFI callback explicitly signals completion.
- Engineers MUST NOT pass raw pointer addresses (`ptr(buffer)`) derived from ephemeral or inline-instantiated TypedArrays directly to non-blocking or multi-threaded FFI calls.
- Engineers MUST ensure that any `JSCallback` or C-side thread pool worker holds a pinned reference token across the entire execution boundary.
- Code MUST explicitly unpin or remove the buffer reference from the lifecycle set only after receiving the completion signal from the native library.
- Components NEVER assume that passing a pointer to an external FFI call keeps the parent JavaScript buffer alive in JavaScriptCore's generational GC.

## Bad vs Good Implementations
### Asynchronous Native File Compression via FFI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The TypedArray buffer is passed as a raw memory address (`ptr(data)`). Because `data` is not explicitly referenced across the async boundary, JavaScriptCore's garbage collector may run while the C thread pool is accessing the memory, causing undefined behavior, silent corruption, or immediate segmentation faults.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

const lib = dlopen("libcompress.so", {
  async_compress: {
    args: [FFIType.ptr, FFIType.u64, FFIType.function],
    returns: FFIType.void,
  },
});

export function compressPayload(data: Uint8Array): Promise<void> {
  return new Promise((resolve) => {
    // ANTI-PATTERN: `data` is passed via raw pointer, but if the caller doesn't retain
    // `data`, JavaScriptCore GC can collect the underlying ArrayBuffer during background
    // C-thread execution, resulting in SIGSEGV or memory corruption.
    lib.symbols.async_compress(ptr(data), data.byteLength, () => {
      resolve();
    });
  });
}
```

#### Production Standard (Correct)
> **Standard**: The buffer is deterministically pinned in `pinnedBuffers` (a module-level GC root) before passing its raw address to the FFI layer. The native completion callback cleans up the pinned reference and closes the `JSCallback` instance safely, guaranteeing the underlying buffer stays alive for the entire duration of the async operation.
```typescript
import { dlopen, FFIType, ptr, JSCallback } from "bun:ffi";

const lib = dlopen("libcompress.so", {
  async_compress: {
    args: [FFIType.ptr, FFIType.u64, FFIType.function],
    returns: FFIType.void,
  },
});

// Root registry anchoring active buffers to prevent premature garbage collection
const pinnedBuffers = new Map<number, Uint8Array>();
let nextOperationId = 1;

export function compressPayload(data: Uint8Array): Promise<void> {
  return new Promise((resolve, reject) => {
    const opId = nextOperationId++;
    pinnedBuffers.set(opId, data); // Explicitly pin reference in GC root set

    let callback: JSCallback | null = null;
    callback = new JSCallback(
      (status: number) => {
        try {
          if (status !== 0) {
            reject(new Error(`Native compression failed with status code ${status}`));
          } else {
            resolve();
          }
        } finally {
          pinnedBuffers.delete(opId); // Deterministically unpin memory after completion
          callback?.close(); // Prevent native callback leak
        }
      },
      {
        args: [FFIType.i32],
        returns: FFIType.void,
      }
    );

    lib.symbols.async_compress(ptr(data), data.byteLength, callback.ptr);
  });
}
```

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 Heap Pointer Pinning and GC Lifespan Management

Bun 1.2 Native FFI Heap Pointer Pinning and GC Lifespan Management defines an industrial-grade behavioral standard for backend engineering. Enforces strict heap memory pinning and explicit reference anchoring during zero-copy asynchronous native FFI invocations in Bun 1.2. JavaScriptCore's garbage collector will eagerly collect unreferenced TypedArrays, reallocating or zeroing underlying memory pages while native C/Rust worker threads read or write to raw pointers, leading to catastrophic memory corruption and segmentation faults. 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: Ephemeral TypedArray Zero-Copy Transfer to Background Native Threads Causing Use-After-Free 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 DriftEphemeral TypedArray Zero-Copy Transfer to Background Native Threads Causing Use-After-FreeCritical
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 anchor TypedArray and Buffer references in a long-lived JavaScript scope, registry, or Map until the native asynchronous FFI callback explicitly signals completion.

Engineers MUST ALWAYS anchor TypedArray and Buffer references in a long-lived JavaScript scope, registry, or Map until the native asynchronous FFI callback explicitly signals completion.

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 pass raw pointer addresses (`ptr(buffer)`) derived from ephemeral or inline-instantiated TypedArrays directly to non-blocking or multi-threaded FFI calls.

Engineers MUST NOT pass raw pointer addresses (`ptr(buffer)`) derived from ephemeral or inline-instantiated TypedArrays directly to non-blocking or multi-threaded FFI 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 ensure that any `JSCallback` or C-side thread pool worker holds a pinned reference token across the entire execution boundary.

Engineers MUST ensure that any `JSCallback` or C-side thread pool worker holds a pinned reference token across the entire execution boundary.

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 unpin or remove the buffer reference from the lifecycle set only after receiving the completion signal from the native library.

Code MUST explicitly unpin or remove the buffer reference from the lifecycle set only after receiving the completion signal from the native library.

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

Components NEVER assume that passing a pointer to an external FFI call keeps the parent JavaScript buffer alive in JavaScriptCore's generational GC.

Components NEVER assume that passing a pointer to an external FFI call keeps the parent JavaScript buffer alive in JavaScriptCore's generational GC.

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 Heap Pointer Pinning and GC Lifespan Management critical for AI coding assistants?

Enforces strict heap memory pinning and explicit reference anchoring during zero-copy asynchronous native FFI invocations in Bun 1.2. JavaScriptCore's garbage collector will eagerly collect unreferenced TypedArrays, reallocating or zeroing underlying memory pages while native C/Rust worker threads read or write to raw pointers, leading to catastrophic memory corruption and segmentation faults. 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 (Ephemeral TypedArray Zero-Copy Transfer to Background Native Threads Causing Use-After-Free) 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