This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-v12-ffi-buffer-pinning-zero-copy-guardrail

Bun 1.2 Native FFI Buffer Pinning and Zero-Copy Lifecycle Guardrail

Prevents catastrophic JavaScriptCore (JSC) heap corruption and use-after-free conditions during non-blocking native C FFI calls in Bun 1.2+. When offloading zero-copy memory buffers across native thread boundaries, buffers must be explicitly pinned outside JSC GC compaction scopes using deterministic lifecycle fences or unmanaged heap pointers (Bun.raw / ptr). Passing raw TypedArray pointers directly across asynchronous FFI boundaries without retaining an active reference or managing an unmanaged lifecycle leads to silent pointer invalidation upon garbage collection.

Prohibited Anti-Pattern: Passing Ephemeral JSC TypedArray Pointers Directly to Asynchronous or Off-Thread Native FFI Operations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native FFI Buffer Pinning and Zero-Copy Lifecycle Guardrail - Prevents catastrophic JavaScriptCore (JSC) heap corruption and use-after-free conditions during non-blocking native C FFI calls in Bun 1.2+. When offloading zero-copy memory buffers across native thread boundaries, buffers must be explicitly pinned outside JSC GC compaction scopes using deterministic lifecycle fences or unmanaged heap pointers (Bun.raw / ptr). Passing raw TypedArray pointers directly across asynchronous FFI boundaries without retaining an active reference or managing an unmanaged lifecycle leads to silent pointer invalidation upon garbage collection.
globs: src/**/*.{ts,js}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-v12-ffi-buffer-pinning-zero-copy-guardrail"
---

# Bun 1.2 Native FFI Buffer Pinning and Zero-Copy Lifecycle Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing Ephemeral JSC TypedArray Pointers Directly to Asynchronous or Off-Thread Native FFI Operations

## System Constraints
You are a Principal Systems Engineer enforcing Bun 1.2 Native FFI Buffer Pinning and Zero-Copy Memory Guardrails. You mandate strict memory fencing, pointer pinning, and allocation lifecycle guarantees when interfacing Bun's JavaScriptCore runtime with native C libraries. Prevent any implicit TypedArray garbage collection while native worker threads hold memory references.

## Strict Guidelines
- Engineers MUST ALWAYS pin or allocate memory via off-heap mechanisms (`new Uint8Array(new SharedArrayBuffer(...))` or `Bun.allocUnsafe` / malloc wrappers) when buffers are read or written asynchronously across native threads.
- Engineers MUST NOT pass `ptr(typedArray)` directly to a native FFI function marked with `threadsafe: true` without holding an explicit JavaScript GC root reference until the native completion callback or promise resolves.
- Engineers MUST maintain an explicit Registry or Set (`PinnedReferenceSet`) to retain root references to active TypedArrays for the entire duration of an in-flight asynchronous FFI invocation.
- Code SHOULD prefer allocating C-managed memory via native FFI malloc/free or Bun's unmanaged pointer APIs for long-running streaming or non-blocking workloads to completely bypass JavaScriptCore GC compaction.
- Native callbacks executed from foreign POSIX threads MUST invoke `JSCallback` wrappers defined via `new JSCallback()` and release their associated pinned references synchronously upon completion.

## Bad vs Good Implementations
### Buffer Pinning Fence for Asynchronous Non-Blocking FFI

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing `ptr(data)` directly to an asynchronous threadsafe FFI function leaves the TypedArray unprotected. Bun's JavaScriptCore garbage collector can relocate or collect `data` during an off-thread execution, resulting in memory corruption, segmentation faults, or silent payload alteration.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

const lib = dlopen("libcrypto_native.so", {
  process_async: {
    args: [FFIType.ptr, FFIType.u64, FFIType.function],
    returns: FFIType.void,
    threadsafe: true,
  },
});

export async function hashPayload(data: Uint8Array): Promise<void> {
  // FAILS: 'data' can be relocated or collected by JSC GC while 'process_async'
  // runs concurrently on a POSIX worker thread, corrupting native memory.
  return new Promise((resolve) => {
    lib.symbols.process_async(
      ptr(data),
      BigInt(data.byteLength),
      () => {
        resolve();
      }
    );
  });
}
```

#### Production Standard (Correct)
> **Standard**: The buffer is deterministically pinned in `activeFfiPins` (a module-level Set acting as a GC root), preventing JavaScriptCore compaction or collection while the off-thread native execution is active. Once the `JSCallback` signals completion, the pin is removed and the callback resource is cleanly closed.
```typescript
import { dlopen, FFIType, ptr, JSCallback } from "bun:ffi";

const lib = dlopen("libcrypto_native.so", {
  process_async: {
    args: [FFIType.ptr, FFIType.u64, FFIType.function],
    returns: FFIType.void,
    threadsafe: true,
  },
});

// Explicit GC root fence to prevent JSC compaction/collection during off-thread operations
const activeFfiPins = new Set<Uint8Array>();

export async function hashPayload(data: Uint8Array): Promise<void> {
  return new Promise((resolve, reject) => {
    // Pin the buffer into an active GC root fence
    activeFfiPins.add(data);

    const cb = new JSCallback(
      (status: number) => {
        try {
          if (status !== 0) reject(new Error(`Native error code: ${status}`));
          else resolve();
        } finally {
          // Release the pin and unref the native callback handle
          activeFfiPins.delete(data);
          cb.close();
        }
      },
      {
        args: [FFIType.i32],
        returns: FFIType.void,
        threadsafe: true,
      }
    );

    lib.symbols.process_async(
      ptr(data),
      BigInt(data.byteLength),
      cb.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 Buffer Pinning and Zero-Copy Lifecycle Guardrail

Bun 1.2 Native FFI Buffer Pinning and Zero-Copy Lifecycle Guardrail defines an industrial-grade behavioral standard for backend engineering. Prevents catastrophic JavaScriptCore (JSC) heap corruption and use-after-free conditions during non-blocking native C FFI calls in Bun 1.2+. When offloading zero-copy memory buffers across native thread boundaries, buffers must be explicitly pinned outside JSC GC compaction scopes using deterministic lifecycle fences or unmanaged heap pointers (Bun.raw / ptr). Passing raw TypedArray pointers directly across asynchronous FFI boundaries without retaining an active reference or managing an unmanaged lifecycle leads to silent pointer invalidation upon garbage collection. 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 TypedArray Pointers Directly to Asynchronous or Off-Thread Native FFI Operations 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 TypedArray Pointers Directly to Asynchronous or Off-Thread Native FFI OperationsCritical
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 pin or allocate memory via off-heap mechanisms (`new Uint8Array(new SharedArrayBuffer(...))` or `Bun.allocUnsafe` / malloc wrappers) when buffers are read or written asynchronously across native threads.

Engineers MUST ALWAYS pin or allocate memory via off-heap mechanisms (`new Uint8Array(new SharedArrayBuffer(...))` or `Bun.allocUnsafe` / malloc wrappers) when buffers are read or written asynchronously across native threads.

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 `ptr(typedArray)` directly to a native FFI function marked with `threadsafe

Engineers MUST NOT pass `ptr(typedArray)` directly to a native FFI function marked with `threadsafe: true` without holding an explicit JavaScript GC root reference until the native completion callback or promise resolves.

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 maintain an explicit Registry or Set (`PinnedReferenceSet`) to retain root references to active TypedArrays for the entire duration of an in-flight asynchronous FFI invocation.

Engineers MUST maintain an explicit Registry or Set (`PinnedReferenceSet`) to retain root references to active TypedArrays for the entire duration of an in-flight asynchronous FFI invocation.

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 prefer allocating C-managed memory via native FFI malloc/free or Bun's unmanaged pointer APIs for long-running streaming or non-blocking workloads to completely bypass JavaScriptCore GC compaction.

Code SHOULD prefer allocating C-managed memory via native FFI malloc/free or Bun's unmanaged pointer APIs for long-running streaming or non-blocking workloads to completely bypass JavaScriptCore GC compaction.

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

Native callbacks executed from foreign POSIX threads MUST invoke `JSCallback` wrappers defined via `new JSCallback()` and release their associated pinned references synchronously upon completion.

Native callbacks executed from foreign POSIX threads MUST invoke `JSCallback` wrappers defined via `new JSCallback()` and release their associated pinned references synchronously upon 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.
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 Buffer Pinning and Zero-Copy Lifecycle Guardrail critical for AI coding assistants?

Prevents catastrophic JavaScriptCore (JSC) heap corruption and use-after-free conditions during non-blocking native C FFI calls in Bun 1.2+. When offloading zero-copy memory buffers across native thread boundaries, buffers must be explicitly pinned outside JSC GC compaction scopes using deterministic lifecycle fences or unmanaged heap pointers (Bun.raw / ptr). Passing raw TypedArray pointers directly across asynchronous FFI boundaries without retaining an active reference or managing an unmanaged lifecycle leads to silent pointer invalidation upon garbage collection. 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 TypedArray Pointers Directly to Asynchronous or Off-Thread Native FFI Operations) 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