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

Bun 1.2 Native C-FFI ArrayBuffer Shared-Memory Lifetime Guardrail

Enforces deterministic ownership contracts and explicit disposal lifecycles when exchanging zero-copy off-heap buffers between Bun's JavaScriptCore runtime and native C/Rust libraries via bun:ffi. Eliminates use-after-free bugs, dangling pointer reads, and fatal double-free corruptions caused by garbage collection uncoordination.

Prohibited Anti-Pattern: Accessing raw native pointers as untracked ArrayBuffers without deterministic pinning or explicit disposal tracking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native C-FFI ArrayBuffer Shared-Memory Lifetime Guardrail - Enforces deterministic ownership contracts and explicit disposal lifecycles when exchanging zero-copy off-heap buffers between Bun's JavaScriptCore runtime and native C/Rust libraries via bun:ffi. Eliminates use-after-free bugs, dangling pointer reads, and fatal double-free corruptions caused by garbage collection uncoordination.
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-shared-memory-lifetime-guardrail"
---

# Bun 1.2 Native C-FFI ArrayBuffer Shared-Memory Lifetime Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Accessing raw native pointers as untracked ArrayBuffers without deterministic pinning or explicit disposal tracking

## System Constraints
You are a Principal Systems and Backend Engineer enforcing Bun 1.2 Native C-FFI ArrayBuffer Shared-Memory Lifetime Guardrails. Mandate strict memory ownership semantics, explicit resource deallocation via Symbol.dispose (Disposable/AsyncDisposable), and unyielding boundaries between native allocators and JavaScriptCore's GC.

## Strict Guidelines
- Engineers MUST ALWAYS wrap native memory allocations in explicit Resource Management types implementing Symbol.dispose or Symbol.asyncDispose to guarantee timely native deallocation.
- Engineers MUST NEVER access a native pointer via toArrayBuffer() or toFastArrayBuffer() after the underlying native buffer has been deallocated or transferred back to native ownership.
- Engineers MUST NEVER pass a GC-managed JavaScript TypedArray pointer (ptr(typedArray)) into asynchronous or long-lived native C/Rust threads without explicit buffer pinning or memory copying.
- Code MUST pair every native allocation helper (e.g., malloc, alloc_slice) with its exact native deallocator function (e.g., free, dealloc_slice) exposed through bun:ffi and invoked inside the dispose lifecycle.
- Services MUST register a FinalizationRegistry fallback for off-heap handles to warn or reclaim memory if a disposable context is leaked, but NEVER rely on GC alone for primary deterministic cleanup.
- Components NEVER store naked Pointer integers across asynchronous ticks without wrapping them in an encapsulated, lifecycle-controlled NativeBuffer reference.

## Bad vs Good Implementations
### Unsafe direct toArrayBuffer without lifecycle management vs. Deterministic Disposable NativeBuffer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The returned Uint8Array references raw native off-heap memory. Because ownership is detached, the native pointer is either leaked indefinitely or prematurely freed by native code while JavaScript still holds a live reference, causing fatal SIGSEGV or silent memory corruption.
```typescript
import { dlopen, FFIType, toArrayBuffer } from "bun:ffi";

const lib = dlopen("libnative.so", {
  create_buffer: { args: [FFIType.usize], returns: FFIType.ptr },
  free_buffer: { args: [FFIType.ptr, FFIType.usize], returns: FFIType.void },
});

export function getSharedData(size: number): Uint8Array {
  const ptr = lib.symbols.create_buffer(size);
  if (!ptr) throw new Error("Native allocation failed");

  // BUG: Returns an unmanaged view over native memory.
  // If free_buffer is called elsewhere, or forgotten, this produces UAF or memory leaks.
  // JavaScriptCore has no knowledge of the backing buffer's lifetime.
  const rawBuffer = toArrayBuffer(ptr, 0, size);
  return new Uint8Array(rawBuffer);
}
```

#### Production Standard (Correct)
> **Standard**: The native memory is encapsulated in ScopedNativeBuffer implementing Symbol.dispose. Once the buffer leaves the 'using' scope, the native free function is invoked and internal pointers are nulled, preventing use-after-free and unbounded off-heap memory leaks.
```typescript
import { dlopen, FFIType, toArrayBuffer, Pointer } from "bun:ffi";

const lib = dlopen("libnative.so", {
  create_buffer: { args: [FFIType.usize], returns: FFIType.ptr },
  free_buffer: { args: [FFIType.ptr, FFIType.usize], returns: FFIType.void },
});

export class ScopedNativeBuffer implements Disposable {
  #ptr: Pointer | null;
  #size: number;
  #view: Uint8Array | null;

  constructor(size: number) {
    this.#ptr = lib.symbols.create_buffer(size);
    if (!this.#ptr) throw new Error("Native allocation failed");
    this.#size = size;
    this.#view = new Uint8Array(toArrayBuffer(this.#ptr, 0, size));
  }

  get data(): Uint8Array {
    if (!this.#ptr || !this.#view) {
      throw new Error("Use-after-free: ScopedNativeBuffer has been disposed");
    }
    return this.#view;
  }

  [Symbol.dispose](): void {
    if (this.#ptr) {
      lib.symbols.free_buffer(this.#ptr, this.#size);
      this.#ptr = null;
      this.#view = null;
    }
  }
}

// Usage with Bun 1.2 / TS 5.2+ Explicit Resource Management:
export function processData(size: number): void {
  using buf = new ScopedNativeBuffer(size);
  buf.data[0] = 42;
  // buf is deterministically freed at end of block; use-after-free is prevented
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Native C-FFI ArrayBuffer Shared-Memory Lifetime Guardrail

Bun 1.2 Native C-FFI ArrayBuffer Shared-Memory Lifetime Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic ownership contracts and explicit disposal lifecycles when exchanging zero-copy off-heap buffers between Bun's JavaScriptCore runtime and native C/Rust libraries via bun:ffi. Eliminates use-after-free bugs, dangling pointer reads, and fatal double-free corruptions caused by garbage collection uncoordination. 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: Accessing raw native pointers as untracked ArrayBuffers without deterministic pinning or explicit disposal tracking 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 DriftAccessing raw native pointers as untracked ArrayBuffers without deterministic pinning or explicit disposal trackingCritical
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 wrap native memory allocations in explicit Resource Management types implementing Symbol.dispose or Symbol.asyncDispose to guarantee timely native deallocation.

Engineers MUST ALWAYS wrap native memory allocations in explicit Resource Management types implementing Symbol.dispose or Symbol.asyncDispose to guarantee timely native deallocation.

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 access a native pointer via toArrayBuffer() or toFastArrayBuffer() after the underlying native buffer has been deallocated or transferred back to native ownership.

Engineers MUST NEVER access a native pointer via toArrayBuffer() or toFastArrayBuffer() after the underlying native buffer has been deallocated or transferred back to native ownership.

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 NEVER pass a GC-managed JavaScript TypedArray pointer (ptr(typedArray)) into asynchronous or long-lived native C/Rust threads without explicit buffer pinning or memory copying.

Engineers MUST NEVER pass a GC-managed JavaScript TypedArray pointer (ptr(typedArray)) into asynchronous or long-lived native C/Rust threads without explicit buffer pinning or memory copying.

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 MUST pair every native allocation helper (e.g., malloc, alloc_slice) with its exact native deallocator function (e.g., free, dealloc_slice) exposed through bun

Code MUST pair every native allocation helper (e.g., malloc, alloc_slice) with its exact native deallocator function (e.g., free, dealloc_slice) exposed through bun:ffi and invoked inside the dispose 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.
5

Services MUST register a FinalizationRegistry fallback for off-heap handles to warn or reclaim memory if a disposable context is leaked, but NEVER rely on GC alone for primary deterministic cleanup.

Services MUST register a FinalizationRegistry fallback for off-heap handles to warn or reclaim memory if a disposable context is leaked, but NEVER rely on GC alone for primary deterministic 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.
6

Components NEVER store naked Pointer integers across asynchronous ticks without wrapping them in an encapsulated, lifecycle-controlled NativeBuffer reference.

Components NEVER store naked Pointer integers across asynchronous ticks without wrapping them in an encapsulated, lifecycle-controlled NativeBuffer 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.
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 C-FFI ArrayBuffer Shared-Memory Lifetime Guardrail critical for AI coding assistants?

Enforces deterministic ownership contracts and explicit disposal lifecycles when exchanging zero-copy off-heap buffers between Bun's JavaScriptCore runtime and native C/Rust libraries via bun:ffi. Eliminates use-after-free bugs, dangling pointer reads, and fatal double-free corruptions caused by garbage collection uncoordination. 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 (Accessing raw native pointers as untracked ArrayBuffers without deterministic pinning or explicit disposal tracking) 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