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

Bun 1.2 FFI Buffer Pinning and JSC GC Isolation Standard

Enforces deterministic lifetime pinning and GC isolation for typed buffers passed across Bun 1.2 FFI boundaries. Prevents JavaScriptCore garbage collection cycles from deallocating or corrupting memory backing active native pointers during synchronous and asynchronous foreign execution.

Prohibited Anti-Pattern: Passing ephemeral TypedArrays inline to FFI functions, allowing JavaScriptCore GC to sweep backing memory under active native pointers.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 FFI Buffer Pinning and JSC GC Isolation Standard - Enforces deterministic lifetime pinning and GC isolation for typed buffers passed across Bun 1.2 FFI boundaries. Prevents JavaScriptCore garbage collection cycles from deallocating or corrupting memory backing active native pointers during synchronous and asynchronous foreign execution.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-native-buffer-pinning-gc-isolation"
---

# Bun 1.2 FFI Buffer Pinning and JSC GC Isolation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing ephemeral TypedArrays inline to FFI functions, allowing JavaScriptCore GC to sweep backing memory under active native pointers.

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 FFI Native Buffer Pinning and GC Isolation. Mandate invariants that prevent premature garbage collection, heap corruption, and dangling pointer faults in foreign function interfaces.

## Strict Guidelines
- Engineers MUST ALWAYS retain strong references to TypedArray or ArrayBuffer instances in an explicit pinning registry or local scope variable until the native invocation and all associated asynchronous tasks fully complete.
- Engineers MUST NOT construct transient TypedArrays inline within FFI call invocations (e.g., `lib.symbols.process(ptr(new Uint8Array(...)))`), as JavaScriptCore can collect the backing store mid-execution.
- Code SHOULD leverage the `using` statement (Explicit Resource Management) or strict `try...finally` cleanup blocks to release buffer pins only after foreign synchronization barriers resolve.
- Services MUST allocate buffers outside the JavaScriptCore GC heap (via foreign `malloc` or native allocators exposed by the C/Rust library) whenever native background worker threads retain pointers across async cycles.
- Components NEVER resize, detach, or reassign typed buffer views while foreign code holds a pointer to the underlying buffer's address space.

## Bad vs Good Implementations
### Asynchronous FFI Buffer Handling and Lifetime Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The source and destination typed arrays are created ephemerally without pinning. JavaScriptCore's conservative garbage collector may sweep or compact unpinned TypedArray backing stores while the foreign asynchronous routine or worker thread still holds raw native pointers, causing memory corruption or segmentation faults.
```typescript
import { dlopen, FFIType, ptr } from 'bun:ffi';

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

export async function compressData(payload: string): Promise<Uint8Array> {
  const encoder = new TextEncoder();
  // ANTI-PATTERN: Inline allocation without variable retention.
  // JSC GC can collect this buffer during native thread execution.
  const outBuf = new Uint8Array(1024 * 1024);
  
  return new Promise((resolve) => {
    lib.symbols.compress_async(
      ptr(encoder.encode(payload)),
      BigInt(payload.length),
      ptr(outBuf)
    );
    // Dangling reference if GC triggers before foreign thread finishes
    setTimeout(() => resolve(outBuf), 100);
  });
}
```

#### Production Standard (Correct)
> **Standard**: Buffer instances are explicitly anchored in a process-wide `pinRegistry` to prevent JSC from sweeping them. The lifecycle is tied to a `JSCallback` fence, and references are only deleted from the registry once the native completion callback is definitively invoked.
```typescript
import { dlopen, FFIType, ptr, JSCallback } from 'bun:ffi';

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

// Pinning registry to preserve GC roots during native async fences
const pinRegistry = new Set<ArrayBufferView>();

export async function compressData(payload: string): Promise<Uint8Array> {
  const inputBuffer = new TextEncoder().encode(payload);
  const outputBuffer = new Uint8Array(1024 * 1024);

  // Pin buffers explicitly to prevent JSC GC collection
  pinRegistry.add(inputBuffer);
  pinRegistry.add(outputBuffer);

  return new Promise<Uint8Array>((resolve, reject) => {
    const onComplete = new JSCallback(
      (status: number) => {
        try {
          if (status !== 0) {
            reject(new Error(`Native compression failed with status: ${status}`));
          } else {
            resolve(new Uint8Array(outputBuffer));
          }
        } finally {
          // Release references only after the native execution barrier signals completion
          pinRegistry.delete(inputBuffer);
          pinRegistry.delete(outputBuffer);
          onComplete.close();
        }
      },
      {
        args: [FFIType.i32],
        returns: FFIType.void,
      }
    );

    lib.symbols.compress_async(
      ptr(inputBuffer),
      BigInt(inputBuffer.byteLength),
      ptr(outputBuffer),
      onComplete.ptr
    );
  });
}
```

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 FFI Buffer Pinning and JSC GC Isolation Standard

Bun 1.2 FFI Buffer Pinning and JSC GC Isolation Standard defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic lifetime pinning and GC isolation for typed buffers passed across Bun 1.2 FFI boundaries. Prevents JavaScriptCore garbage collection cycles from deallocating or corrupting memory backing active native pointers during synchronous and asynchronous foreign execution. 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 TypedArrays inline to FFI functions, allowing JavaScriptCore GC to sweep backing memory under active native pointers. 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 TypedArrays inline to FFI functions, allowing JavaScriptCore GC to sweep backing memory under active native pointers.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 ALWAYS retain strong references to TypedArray or ArrayBuffer instances in an explicit pinning registry or local scope variable until the native invocation and all associated asynchronous tasks fully complete.

Engineers MUST ALWAYS retain strong references to TypedArray or ArrayBuffer instances in an explicit pinning registry or local scope variable until the native invocation and all associated asynchronous tasks fully complete.

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 construct transient TypedArrays inline within FFI call invocations (e.g., `lib.symbols.process(ptr(new Uint8Array(...)))`), as JavaScriptCore can collect the backing store mid-execution.

Engineers MUST NOT construct transient TypedArrays inline within FFI call invocations (e.g., `lib.symbols.process(ptr(new Uint8Array(...)))`), as JavaScriptCore can collect the backing store mid-execution.

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

Code SHOULD leverage the `using` statement (Explicit Resource Management) or strict `try...finally` cleanup blocks to release buffer pins only after foreign synchronization barriers resolve.

Code SHOULD leverage the `using` statement (Explicit Resource Management) or strict `try...finally` cleanup blocks to release buffer pins only after foreign synchronization barriers resolve.

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

Services MUST allocate buffers outside the JavaScriptCore GC heap (via foreign `malloc` or native allocators exposed by the C/Rust library) whenever native background worker threads retain pointers across async cycles.

Services MUST allocate buffers outside the JavaScriptCore GC heap (via foreign `malloc` or native allocators exposed by the C/Rust library) whenever native background worker threads retain pointers across async cycles.

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 resize, detach, or reassign typed buffer views while foreign code holds a pointer to the underlying buffer's address space.

Components NEVER resize, detach, or reassign typed buffer views while foreign code holds a pointer to the underlying buffer's address space.

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 FFI Buffer Pinning and JSC GC Isolation Standard critical for AI coding assistants?

Enforces deterministic lifetime pinning and GC isolation for typed buffers passed across Bun 1.2 FFI boundaries. Prevents JavaScriptCore garbage collection cycles from deallocating or corrupting memory backing active native pointers during synchronous and asynchronous foreign execution. 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 TypedArrays inline to FFI functions, allowing JavaScriptCore GC to sweep backing memory under active native pointers.) 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