This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-ffi-pointer-lifecycle-invariant

Bun 1.2 Zero-Copy Buffer C-FFI Pointer Lifecycle Invariant

Enforces strict pinning and deterministic lifecycle management of off-heap memory buffers passed across Bun's JavaScript runtime and native C-FFI boundaries. JavaScriptCore GC compaction can relocate or collect backed ArrayBuffers, causing use-after-free conditions and memory corruption when native async C code dereferences raw pointers.

Prohibited Anti-Pattern: Ephemeral TypedArray Pointer Passing to Asynchronous C-FFI Invocations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy Buffer C-FFI Pointer Lifecycle Invariant - Enforces strict pinning and deterministic lifecycle management of off-heap memory buffers passed across Bun's JavaScript runtime and native C-FFI boundaries. JavaScriptCore GC compaction can relocate or collect backed ArrayBuffers, causing use-after-free conditions and memory corruption when native async C code dereferences raw pointers.
globs: src/**/*.{ts,js,mts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-pointer-lifecycle-invariant"
---

# Bun 1.2 Zero-Copy Buffer C-FFI Pointer Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Ephemeral TypedArray Pointer Passing to Asynchronous C-FFI Invocations

## System Constraints
You are a Principal Systems Engineer enforcing strict off-heap memory safety in Bun 1.2 C-FFI bindings. Mandate invariants that prevent garbage collection compaction, premature deallocation, and dangling pointers when exposing TypedArray buffers and raw pointers to native C ABI boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS retain an explicit in-memory reference to the underlying Uint8Array or ArrayBuffer until native C execution or asynchronous callback returns.
- Engineers MUST NOT pass `ptr(buffer)` directly into native async functions without pinning the backing object in an active Scope, Set, or FinalizationRegistry handle.
- Code MUST use `Bun.allocUnsafe` or explicit off-heap C memory allocation when raw pointer lifetimes must outlive the synchronous JavaScript call frame.
- Services MUST deallocate manually allocated off-heap pointers via corresponding native free functions (e.g., custom free or `libc.free`) to eliminate native memory leaks.
- Components NEVER assume JavaScript TypedArray pointer stability across microtask checkpoints unless wrapped in a pinned lifetime guard.

## Bad vs Good Implementations
### Prevent GC Reclaiming Buffer During Asynchronous FFI Task

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The local `serialized` Uint8Array is eligible for garbage collection or heap compaction as soon as `dispatchData` exits. When the asynchronous native C thread dereferences `rawPtr`, it causes a use-after-free or memory corruption crash.
```typescript
import { cc, ptr } from 'bun:ffi';

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

export function dispatchData(data: Record<string, unknown>) {
  // Anti-Pattern: Buffer allocated in local scope, unpinned across async C execution
  const serialized = new TextEncoder().encode(JSON.stringify(data));
  const rawPtr = ptr(serialized);

  lib.symbols.process_async(rawPtr, serialized.byteLength, () => {
    // GC may have relocated or collected 'serialized' before C completed processing
    console.log('Async processing finished');
  });
}
```

#### Production Standard (Correct)
> **Standard**: The underlying `serialized` Uint8Array is anchored in `pinnedHandles`, keeping it rooted in the JavaScriptCore GC graph. Once the native task triggers the callback, the buffer is explicitly unpinned and the `JSCallback` handle is closed.
```typescript
import { cc, ptr, JSCallback } from 'bun:ffi';

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

// Pinned registry guaranteeing GC root retention across async call boundary
const pinnedHandles = new Set<Uint8Array>();

export function dispatchData(data: Record<string, unknown>): Promise<void> {
  return new Promise((resolve, reject) => {
    const serialized = new TextEncoder().encode(JSON.stringify(data));
    pinnedHandles.add(serialized);
    const rawPtr = ptr(serialized);

    const cb = new JSCallback((err: number) => {
      pinnedHandles.delete(serialized);
      cb.close();
      if (err !== 0) reject(new Error(`Native error code: ${err}`));
      else resolve();
    }, {
      args: ['int'],
      returns: 'void',
    });

    lib.symbols.process_async(rawPtr, serialized.byteLength, cb.ptr);
  });
}
```

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 Zero-Copy Buffer C-FFI Pointer Lifecycle Invariant

Bun 1.2 Zero-Copy Buffer C-FFI Pointer Lifecycle Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict pinning and deterministic lifecycle management of off-heap memory buffers passed across Bun's JavaScript runtime and native C-FFI boundaries. JavaScriptCore GC compaction can relocate or collect backed ArrayBuffers, causing use-after-free conditions and memory corruption when native async C code dereferences 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: Ephemeral TypedArray Pointer Passing to Asynchronous C-FFI Invocations 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 TypedArray Pointer Passing to Asynchronous C-FFI InvocationsCritical
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 explicit in-memory reference to the underlying Uint8Array or ArrayBuffer until native C execution or asynchronous callback returns.

Engineers MUST ALWAYS retain an explicit in-memory reference to the underlying Uint8Array or ArrayBuffer until native C execution or asynchronous callback returns.

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 `ptr(buffer)` directly into native async functions without pinning the backing object in an active Scope, Set, or FinalizationRegistry handle.

Engineers MUST NOT pass `ptr(buffer)` directly into native async functions without pinning the backing object in an active Scope, Set, or FinalizationRegistry handle.

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 use `Bun.allocUnsafe` or explicit off-heap C memory allocation when raw pointer lifetimes must outlive the synchronous JavaScript call frame.

Code MUST use `Bun.allocUnsafe` or explicit off-heap C memory allocation when raw pointer lifetimes must outlive the synchronous JavaScript call frame.

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 deallocate manually allocated off-heap pointers via corresponding native free functions (e.g., custom free or `libc.free`) to eliminate native memory leaks.

Services MUST deallocate manually allocated off-heap pointers via corresponding native free functions (e.g., custom free or `libc.free`) to eliminate native memory leaks.

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 TypedArray pointer stability across microtask checkpoints unless wrapped in a pinned lifetime guard.

Components NEVER assume JavaScript TypedArray pointer stability across microtask checkpoints unless wrapped in a pinned lifetime guard.

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 Zero-Copy Buffer C-FFI Pointer Lifecycle Invariant critical for AI coding assistants?

Enforces strict pinning and deterministic lifecycle management of off-heap memory buffers passed across Bun's JavaScript runtime and native C-FFI boundaries. JavaScriptCore GC compaction can relocate or collect backed ArrayBuffers, causing use-after-free conditions and memory corruption when native async C code dereferences 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 (Ephemeral TypedArray Pointer Passing to Asynchronous C-FFI Invocations) 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