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

Bun 1.2 Native FFI C-ABI Off-Heap Memory Ownership Protocol

Enforces deterministic lifecycle management and strict single-owner semantics for off-heap native memory allocated via Bun 1.2 FFI. Eliminates silent use-after-free segmentation faults and off-heap RSS memory exhaustion when high-throughput event loops interface with native C/Rust shared libraries. Mandates TC39 Explicit Resource Management alongside FinalizationRegistry fail-safes for non-trivial native allocations.

Prohibited Anti-Pattern: Unmanaged C-Allocated Pointers Exposed Directly to JavaScript Event Loop Contexts Without Deterministic Deallocation Lifecycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native FFI C-ABI Off-Heap Memory Ownership Protocol - Enforces deterministic lifecycle management and strict single-owner semantics for off-heap native memory allocated via Bun 1.2 FFI. Eliminates silent use-after-free segmentation faults and off-heap RSS memory exhaustion when high-throughput event loops interface with native C/Rust shared libraries. Mandates TC39 Explicit Resource Management alongside FinalizationRegistry fail-safes for non-trivial native allocations.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-native-ffi-cabi-memory-ownership"
---

# Bun 1.2 Native FFI C-ABI Off-Heap Memory Ownership Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unmanaged C-Allocated Pointers Exposed Directly to JavaScript Event Loop Contexts Without Deterministic Deallocation Lifecycles

## System Constraints
You are a Principal Systems Architect enforcing the Bun 1.2 Native FFI C-ABI Off-Heap Memory Ownership Protocol. You must reject any FFI bindings that yield raw unmanaged pointers directly to consumer code, rely solely on V8/JSC GC finalizers for deallocation under high throughput, or perform zero-copy buffer sharing across asynchronous tick boundaries without active pinning and deterministic cleanup.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate foreign pointers in an explicit resource wrapper implementing TypeScript 5.2+ `[Symbol.dispose]` or `[Symbol.asyncDispose]`.
- Engineers MUST NEVER permit JavaScript asynchronous microtasks to access native off-heap memory via `toArrayBuffer()` without defensive copying or maintaining an explicit, incremented native ref-count until the promise settles.
- Code MUST register an emergency fallback deallocator via `FinalizationRegistry` to log memory leaks and release C-heap blocks if the consumer misses explicit disposal.
- Services MUST verify foreign function pointer addresses for `0` (NULL) prior to invoking `toArrayBuffer()`, `read()`, or dereferencing via `bun:ffi`.
- Components NEVER store naked integer pointers (`number` or `bigint`) in long-lived state structures; pointers must remain encapsulated inside strict ownership wrappers.

## Bad vs Good Implementations
### Deterministic Off-Heap Memory Ownership via Explicit Resource Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native pointer is directly exposed and manipulated across an async microtask boundary. If the fetch operation throws or rejects, `crypto_free_payload` is bypassed, leaking off-heap C memory. If freed concurrently, `view` points to deallocated memory, causing a fatal segmentation fault.
```typescript
import { dlopen, FFIType, ptr, toArrayBuffer } from "bun:ffi";

const lib = dlopen("libcrypto_core.so", {
  crypto_generate_payload: {
    args: [FFIType.u32],
    returns: FFIType.ptr,
  },
  crypto_free_payload: {
    args: [FFIType.ptr],
    returns: FFIType.void,
  },
});

export async function processPayload(size: number) {
  // DANGEROUS: Returning raw pointer, converting to buffer without ownership tracking.
  // If this async operation yields to the event loop, memory leaks if not freed,
  // or causes a SIGSEGV if another routine calls crypto_free_payload prematurely.
  const rawPtr = lib.symbols.crypto_generate_payload(size);
  if (!rawPtr) throw new Error("Native allocation failed");

  const view = new Uint8Array(toArrayBuffer(rawPtr, 0, size));
  await fetch("https://analytics.internal/ingest", {
    method: "POST",
    body: view,
  });

  // Unreachable if fetch throws, causing an off-heap RSS leak
  lib.symbols.crypto_free_payload(rawPtr);
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the foreign pointer in an RAII container adhering to TC39 `Disposable`. The native memory is freed deterministically when exiting lexical scope, even on exceptions. A `FinalizationRegistry` serves as an emergency catch for missed disposals, and defensive copying guarantees zero-copy view invalidation across async ticks.
```typescript
import { dlopen, FFIType, ptr, toArrayBuffer, Pointer } from "bun:ffi";

const lib = dlopen("libcrypto_core.so", {
  crypto_generate_payload: {
    args: [FFIType.u32],
    returns: FFIType.ptr,
  },
  crypto_free_payload: {
    args: [FFIType.ptr],
    returns: FFIType.void,
  },
});

const registry = new FinalizationRegistry<Pointer>((heldPtr) => {
  console.error(`[LEAK WARNING] Unmanaged native pointer at 0x${heldPtr.toString(16)} freed by GC fallback.`);
  lib.symbols.crypto_free_payload(heldPtr);
});

export class NativeBuffer implements Disposable {
  #ptr: Pointer | null;
  readonly byteLength: number;

  constructor(size: number) {
    const rawPtr = lib.symbols.crypto_generate_payload(size);
    if (!rawPtr || rawPtr === 0) {
      throw new Error(`Failed to allocate native off-heap buffer of size ${size}`);
    }
    this.#ptr = rawPtr;
    this.byteLength = size;
    registry.register(this, rawPtr, this);
  }

  get bytes(): Uint8Array {
    if (!this.#ptr) throw new Error("Use-after-free: Native buffer is already disposed");
    // Safe view bounded strictly to allocated span
    return new Uint8Array(toArrayBuffer(this.#ptr, 0, this.byteLength));
  }

  [Symbol.dispose](): void {
    if (this.#ptr) {
      const ptrToFree = this.#ptr;
      this.#ptr = null;
      registry.unregister(this);
      lib.symbols.crypto_free_payload(ptrToFree);
    }
  }
}

export async function processPayload(size: number): Promise<void> {
  // Guaranteed deterministic deallocation via TC39 'using'
  using nativeBuffer = new NativeBuffer(size);
  
  // Copy to isolated typed array before dispatching across asynchronous event loop boundaries
  const safeCopy = new Uint8Array(nativeBuffer.bytes);
  
  await fetch("https://analytics.internal/ingest", {
    method: "POST",
    body: safeCopy,
  });
}
```

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 C-ABI Off-Heap Memory Ownership Protocol

Bun 1.2 Native FFI C-ABI Off-Heap Memory Ownership Protocol defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic lifecycle management and strict single-owner semantics for off-heap native memory allocated via Bun 1.2 FFI. Eliminates silent use-after-free segmentation faults and off-heap RSS memory exhaustion when high-throughput event loops interface with native C/Rust shared libraries. Mandates TC39 Explicit Resource Management alongside FinalizationRegistry fail-safes for non-trivial native allocations. 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: Unmanaged C-Allocated Pointers Exposed Directly to JavaScript Event Loop Contexts Without Deterministic Deallocation Lifecycles 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 DriftUnmanaged C-Allocated Pointers Exposed Directly to JavaScript Event Loop Contexts Without Deterministic Deallocation LifecyclesCritical
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 encapsulate foreign pointers in an explicit resource wrapper implementing TypeScript 5.2+ `[Symbol.dispose]` or `[Symbol.asyncDispose]`.

Engineers MUST ALWAYS encapsulate foreign pointers in an explicit resource wrapper implementing TypeScript 5.2+ `[Symbol.dispose]` or `[Symbol.asyncDispose]`.

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 NEVER permit JavaScript asynchronous microtasks to access native off-heap memory via `toArrayBuffer()` without defensive copying or maintaining an explicit, incremented native ref-count until the promise settles.

Engineers MUST NEVER permit JavaScript asynchronous microtasks to access native off-heap memory via `toArrayBuffer()` without defensive copying or maintaining an explicit, incremented native ref-count until the promise settles.

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 MUST register an emergency fallback deallocator via `FinalizationRegistry` to log memory leaks and release C-heap blocks if the consumer misses explicit disposal.

Code MUST register an emergency fallback deallocator via `FinalizationRegistry` to log memory leaks and release C-heap blocks if the consumer misses explicit disposal.

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 verify foreign function pointer addresses for `0` (NULL) prior to invoking `toArrayBuffer()`, `read()`, or dereferencing via `bun

Services MUST verify foreign function pointer addresses for `0` (NULL) prior to invoking `toArrayBuffer()`, `read()`, or dereferencing via `bun:ffi`.

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 store naked integer pointers (`number` or `bigint`) in long-lived state structures

Components NEVER store naked integer pointers (`number` or `bigint`) in long-lived state structures; pointers must remain encapsulated inside strict ownership wrappers.

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 C-ABI Off-Heap Memory Ownership Protocol critical for AI coding assistants?

Enforces deterministic lifecycle management and strict single-owner semantics for off-heap native memory allocated via Bun 1.2 FFI. Eliminates silent use-after-free segmentation faults and off-heap RSS memory exhaustion when high-throughput event loops interface with native C/Rust shared libraries. Mandates TC39 Explicit Resource Management alongside FinalizationRegistry fail-safes for non-trivial native allocations. 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 (Unmanaged C-Allocated Pointers Exposed Directly to JavaScript Event Loop Contexts Without Deterministic Deallocation Lifecycles) 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