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

Bun 1.2 FFI Buffer Lifetime and Non-GC Pinning Standard

Enforces explicit memory retention and pointer pinning across the JavaScriptCore-to-native C ABI boundary in Bun 1.2 FFI integrations. Prevents silent memory compaction and garbage collection sweeps from invalidating raw buffer pointers during asynchronous or microtask-heavy native execution.

Prohibited Anti-Pattern: Ephemeral Inline Buffer Passing to Native FFI Boundary Causing Silent GC Use-After-Free

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 FFI Buffer Lifetime and Non-GC Pinning Standard - Enforces explicit memory retention and pointer pinning across the JavaScriptCore-to-native C ABI boundary in Bun 1.2 FFI integrations. Prevents silent memory compaction and garbage collection sweeps from invalidating raw buffer pointers during asynchronous or microtask-heavy native execution.
globs: src/**/*.{ts,js}, lib/**/*.{ts,js}, native/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-buffer-lifetime-pinning-standard"
---

# Bun 1.2 FFI Buffer Lifetime and Non-GC Pinning Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ephemeral Inline Buffer Passing to Native FFI Boundary Causing Silent GC Use-After-Free

## System Constraints
You are a Principal Systems Engineer enforcing strict FFI memory safety in Bun 1.2. The JavaScriptCore (JSC) garbage collector can collect or relocate typed array backing stores across microtask ticks unless deterministically pinned. You must enforce explicit buffer pinning, deterministic native memory management via 'using' resource scopes (Symbol.dispose), and forbid inline typed array instantiation inside CFunction invocations.

## Strict Guidelines
- Engineers MUST NEVER pass inline instantiated TypedArrays directly into 'ptr()' or FFI native functions (e.g., ffiFn(ptr(new Uint8Array(1024)))) without an outer scope-retaining reference.
- Engineers MUST pin any JavaScript-allocated buffer passed to asynchronous or non-blocking C ABI tasks in a module-level 'Set<ArrayBuffer | Uint8Array>' or an explicit Lifetime Registry until the native callback fires.
- Services MUST prefer native allocations via 'Bun.allocUnsafe()' or direct C-side allocation when buffers cross asynchronous boundaries or exceed microtask boundaries.
- Code interacting with synchronous C ABI functions SHOULD wrap raw pointers in deterministic RAII lifecycle objects implementing 'Symbol.dispose' to guarantee bounds validation and immediate manual cleanup.
- Components NEVER assume JavaScript typed array pointers remain stable across await boundaries or nested Promise chains.

## Bad vs Good Implementations
### Pinning Buffers Across Native ABI Boundary Using Disposable Scope

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Inline `Buffer.from(data)` is eligible for garbage collection immediately after `ptr(...)` evaluates. If JSC performs a nursery GC sweep or memory compaction while `process_payload` executes (or if `process_payload` retains the pointer across thread pools), the pointer points to freed or relocated memory, causing segfaults or corrupted writes.
```typescript
import { cc, ptr } from 'bun:ffi';

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

export async function computeHash(data: string): Promise<void> {
  // ANTI-PATTERN: Buffer allocated inline and referenced only via ptr().
  // JSC GC can sweep the TypedArray backing store during event-loop microtasks
  // while native code executes or holds the raw memory address.
  symbols.process_payload(ptr(Buffer.from(data)), Buffer.byteLength(data));
  await Bun.sleep(1);
}
```

#### Production Standard (Correct)
> **Standard**: The `PinnedBuffer` keeps an explicit reference in `activePins` (a module-level GC root), preventing JSC from collecting or moving the backing ArrayBuffer. Using TypeScript 5.2+ `using pinned = ...` guarantees deterministic unpinning via `Symbol.dispose` at scope exit, even under errors or concurrent microtask yields.
```typescript
import { cc, ptr } from 'bun:ffi';

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

class PinnedBuffer implements Disposable {
  public readonly buffer: Uint8Array;
  public readonly pointer: number;
  public readonly length: number;

  constructor(source: string | Uint8Array) {
    this.buffer = typeof source === 'string' ? new TextEncoder().encode(source) : source;
    this.length = this.buffer.byteLength;
    this.pointer = ptr(this.buffer);
    // Force JSC GC roots to retain the backing ArrayBuffer
    PinnedBuffer.activePins.add(this.buffer);
  }

  [Symbol.dispose](): void {
    PinnedBuffer.activePins.delete(this.buffer);
  }

  private static readonly activePins = new Set<Uint8Array>();
}

export async function computeHash(data: string): Promise<void> {
  // INVARIANT FIX: Deterministic pinning ensures the buffer is reachable
  // by the GC root Set for the full lexical lifetime of the operation.
  using pinned = new PinnedBuffer(data);
  symbols.process_payload(pinned.pointer, pinned.length);
  await Bun.sleep(1);
}
```

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 FFI Buffer Lifetime and Non-GC Pinning Standard

Bun 1.2 FFI Buffer Lifetime and Non-GC Pinning Standard defines an industrial-grade behavioral standard for backend engineering. Enforces explicit memory retention and pointer pinning across the JavaScriptCore-to-native C ABI boundary in Bun 1.2 FFI integrations. Prevents silent memory compaction and garbage collection sweeps from invalidating raw buffer pointers during asynchronous or microtask-heavy native 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: Ephemeral Inline Buffer Passing to Native FFI Boundary Causing Silent GC 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 Inline Buffer Passing to Native FFI Boundary Causing Silent GC 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 NEVER pass inline instantiated TypedArrays directly into 'ptr()' or FFI native functions (e.g., ffiFn(ptr(new Uint8Array(1024)))) without an outer scope-retaining reference.

Engineers MUST NEVER pass inline instantiated TypedArrays directly into 'ptr()' or FFI native functions (e.g., ffiFn(ptr(new Uint8Array(1024)))) without an outer scope-retaining reference.

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 pin any JavaScript-allocated buffer passed to asynchronous or non-blocking C ABI tasks in a module-level 'Set<ArrayBuffer | Uint8Array>' or an explicit Lifetime Registry until the native callback fires.

Engineers MUST pin any JavaScript-allocated buffer passed to asynchronous or non-blocking C ABI tasks in a module-level 'Set<ArrayBuffer | Uint8Array>' or an explicit Lifetime Registry until the native callback fires.

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

Services MUST prefer native allocations via 'Bun.allocUnsafe()' or direct C-side allocation when buffers cross asynchronous boundaries or exceed microtask boundaries.

Services MUST prefer native allocations via 'Bun.allocUnsafe()' or direct C-side allocation when buffers cross asynchronous boundaries or exceed microtask 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.
4

Code interacting with synchronous C ABI functions SHOULD wrap raw pointers in deterministic RAII lifecycle objects implementing 'Symbol.dispose' to guarantee bounds validation and immediate manual cleanup.

Code interacting with synchronous C ABI functions SHOULD wrap raw pointers in deterministic RAII lifecycle objects implementing 'Symbol.dispose' to guarantee bounds validation and immediate manual cleanup.

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 JavaScript typed array pointers remain stable across await boundaries or nested Promise chains.

Components NEVER assume JavaScript typed array pointers remain stable across await boundaries or nested Promise chains.

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 Lifetime and Non-GC Pinning Standard critical for AI coding assistants?

Enforces explicit memory retention and pointer pinning across the JavaScriptCore-to-native C ABI boundary in Bun 1.2 FFI integrations. Prevents silent memory compaction and garbage collection sweeps from invalidating raw buffer pointers during asynchronous or microtask-heavy native 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 (Ephemeral Inline Buffer Passing to Native FFI Boundary Causing Silent GC 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