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

Bun 1.2 Native FFI Pinned Buffer Memory Ownership Fence

Enforces deterministic memory ownership and explicit buffer pinning across Bun 1.2 JavaScriptCore (JSC) and native C/Rust FFI boundaries. Prevents catastrophic use-after-free vulnerabilities, memory corruption, and runtime SIGSEGV crashes caused by JSC garbage collection and heap compaction sweeps reclaiming shared memory while native threads operate on raw pointers.

Prohibited Anti-Pattern: Passing Ephemeral TypedArrays Directly to Native FFI Without Explicit Lifetime Anchoring or Manual Allocator Fencing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native FFI Pinned Buffer Memory Ownership Fence - Enforces deterministic memory ownership and explicit buffer pinning across Bun 1.2 JavaScriptCore (JSC) and native C/Rust FFI boundaries. Prevents catastrophic use-after-free vulnerabilities, memory corruption, and runtime SIGSEGV crashes caused by JSC garbage collection and heap compaction sweeps reclaiming shared memory while native threads operate on raw pointers.
globs: src/**/*.{ts,js}, lib/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-pinned-buffer-memory-fence"
---

# Bun 1.2 Native FFI Pinned Buffer Memory Ownership Fence

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing Ephemeral TypedArrays Directly to Native FFI Without Explicit Lifetime Anchoring or Manual Allocator Fencing

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-tolerance memory invariants in Bun 1.2 native FFI integrations. JavaScriptCore (JSC) garbage collection operates concurrently and can sweep, relocate, or reclaim ArrayBuffers if not explicitly pinned or anchored during native operations. You must mandate strict memory fences, explicit reference lifecycles via TypeScript explicit resource management (using statement) or deterministic retention bags, and ensure all native buffers crossing the boundary maintain guaranteed liveness until native execution signals completion.

## Strict Guidelines
- Engineers MUST ALWAYS retain an un-collectible JavaScript reference (pinned anchor) to any TypedArray or ArrayBuffer passed to an asynchronous or threaded native FFI function until the native completion callback executes.
- Engineers MUST NOT pass inline transient buffer allocations (e.g., `fn(ptr(new Uint8Array(n)))`) directly across FFI boundaries if the native extension accesses the pointer asynchronously or stores it internally.
- Code SHOULD implement TypeScript 5.2+ Explicit Resource Management (`using` / `Symbol.dispose` / `Symbol.asyncDispose`) to fence native buffer lifetimes deterministically and prevent leakages on error branches.
- Services MUST allocate long-lived or cross-thread shared memory via native allocators (`Bun.allocUnsafe` or native C/Rust allocators returned as opaque pointers) rather than trusting GC-managed TypedArray heaps across unbounded boundaries.
- Components NEVER cast raw pointers (`bun:ffi` `ptr()`) back to ArrayBuffers (`toArrayBuffer()`) without providing an explicit byte offset and bounded byte length corresponding exactly to the active allocation lifecycle.

## Bad vs Good Implementations
### Unanchored Ephemeral Buffer Passing vs. Deterministic Pinned Lifetime Fence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing an inline or locally scoped TypedArray to an asynchronous FFI call without pinning allows JavaScriptCore to garbage-collect the underlying ArrayBuffer while the native worker thread is still reading or writing to the raw memory address, leading to use-after-free and process crashes.
```typescript
import { cc, ptr } from 'bun:ffi';

const { symbols } = cc({
  source: './native_crypto.c',
  symbols: {
    process_payload_async: {
      args: ['ptr', 'usize', 'callback'],
      returns: 'void',
    },
  },
});

export function dispatchJob(payload: string): void {
  // CRITICAL BUG: TypedArray is allocated ephemerally in the JSC heap.
  // A GC sweep during async C/Rust execution will relocate or collect
  // the underlying buffer, inducing a runtime SIGSEGV or memory corruption.
  const buffer = new TextEncoder().encode(payload);
  
  symbols.process_payload_async(
    ptr(buffer),
    buffer.byteLength,
    () => {
      console.log('Processing completed');
    }
  );
}
```

#### Production Standard (Correct)
> **Standard**: The PinnedBufferFence holds a hard reference to the buffer in a module-scoped Set (`pinnedRegistry`), ensuring JavaScriptCore GC cannot sweep the underlying memory while the native thread executes. Once the native callback confirms task termination, the anchor is safely disposed.
```typescript
import { cc, ptr, JSCallback } from 'bun:ffi';

const { symbols } = cc({
  source: './native_crypto.c',
  symbols: {
    process_payload_async: {
      args: ['ptr', 'usize', 'callback'],
      returns: 'void',
    },
  },
});

// Explicit Pinned Buffer Fence using deterministic lifecycle tracking
class PinnedBufferFence implements Disposable {
  public readonly buffer: Uint8Array;
  public readonly rawPtr: number;
  private static pinnedRegistry = new Set<PinnedBufferFence>();

  constructor(source: Uint8Array) {
    this.buffer = source;
    this.rawPtr = ptr(this.buffer);
    // Anchor reference to prevent JavaScriptCore GC reclamation
    PinnedBufferFence.pinnedRegistry.add(this);
  }

  [Symbol.dispose](): void {
    PinnedBufferFence.pinnedRegistry.delete(this);
  }
}

export async function dispatchJob(payload: string): Promise<void> {
  const encoded = new TextEncoder().encode(payload);
  const fence = new PinnedBufferFence(encoded);

  return new Promise<void>((resolve, reject) => {
    const cb = new JSCallback(
      (errCode: number) => {
        // Explicitly release the pinned anchor only after native boundary completion
        fence[Symbol.dispose]();
        cb.close();
        if (errCode !== 0) reject(new Error(`Native error: ${errCode}`));
        else resolve();
      },
      { args: ['i32'], returns: 'void' }
    );

    symbols.process_payload_async(fence.rawPtr, fence.buffer.byteLength, cb);
  });
}
```

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 Native FFI Pinned Buffer Memory Ownership Fence

Bun 1.2 Native FFI Pinned Buffer Memory Ownership Fence defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic memory ownership and explicit buffer pinning across Bun 1.2 JavaScriptCore (JSC) and native C/Rust FFI boundaries. Prevents catastrophic use-after-free vulnerabilities, memory corruption, and runtime SIGSEGV crashes caused by JSC garbage collection and heap compaction sweeps reclaiming shared memory while native threads operate on 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 TypedArrays Directly to Native FFI Without Explicit Lifetime Anchoring or Manual Allocator Fencing 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 Directly to Native FFI Without Explicit Lifetime Anchoring or Manual Allocator FencingCritical
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 an un-collectible JavaScript reference (pinned anchor) to any TypedArray or ArrayBuffer passed to an asynchronous or threaded native FFI function until the native completion callback executes.

Engineers MUST ALWAYS retain an un-collectible JavaScript reference (pinned anchor) to any TypedArray or ArrayBuffer passed to an asynchronous or threaded native FFI function until the native completion callback executes.

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 inline transient buffer allocations (e.g., `fn(ptr(new Uint8Array(n)))`) directly across FFI boundaries if the native extension accesses the pointer asynchronously or stores it internally.

Engineers MUST NOT pass inline transient buffer allocations (e.g., `fn(ptr(new Uint8Array(n)))`) directly across FFI boundaries if the native extension accesses the pointer asynchronously or stores it internally.

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 implement TypeScript 5.2+ Explicit Resource Management (`using` / `Symbol.dispose` / `Symbol.asyncDispose`) to fence native buffer lifetimes deterministically and prevent leakages on error branches.

Code SHOULD implement TypeScript 5.2+ Explicit Resource Management (`using` / `Symbol.dispose` / `Symbol.asyncDispose`) to fence native buffer lifetimes deterministically and prevent leakages on error branches.

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 long-lived or cross-thread shared memory via native allocators (`Bun.allocUnsafe` or native C/Rust allocators returned as opaque pointers) rather than trusting GC-managed TypedArray heaps across unbounded boundaries.

Services MUST allocate long-lived or cross-thread shared memory via native allocators (`Bun.allocUnsafe` or native C/Rust allocators returned as opaque pointers) rather than trusting GC-managed TypedArray heaps across unbounded boundaries.

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 cast raw pointers (`bun

Components NEVER cast raw pointers (`bun:ffi` `ptr()`) back to ArrayBuffers (`toArrayBuffer()`) without providing an explicit byte offset and bounded byte length corresponding exactly to the active allocation lifecycle.

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 Pinned Buffer Memory Ownership Fence critical for AI coding assistants?

Enforces deterministic memory ownership and explicit buffer pinning across Bun 1.2 JavaScriptCore (JSC) and native C/Rust FFI boundaries. Prevents catastrophic use-after-free vulnerabilities, memory corruption, and runtime SIGSEGV crashes caused by JSC garbage collection and heap compaction sweeps reclaiming shared memory while native threads operate on 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 TypedArrays Directly to Native FFI Without Explicit Lifetime Anchoring or Manual Allocator Fencing) 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