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

Bun 1.2 Native C-FFI Pointer Lifecycle Pinning & GC Anchoring

Enforces strict heap anchoring for typed arrays, buffers, and native pointers bridged to C dynamic libraries via `bun:ffi`. Prevents catastrophic use-after-free, memory corruption, and silent segmentation faults triggered by JavaScriptCore garbage collection sweeps during zero-copy asynchronous native execution.

Prohibited Anti-Pattern: Passing Unanchored JavaScript Allocations as Zero-Copy Raw C-Pointers Across Async FFI Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native C-FFI Pointer Lifecycle Pinning & GC Anchoring - Enforces strict heap anchoring for typed arrays, buffers, and native pointers bridged to C dynamic libraries via `bun:ffi`. Prevents catastrophic use-after-free, memory corruption, and silent segmentation faults triggered by JavaScriptCore garbage collection sweeps during zero-copy asynchronous native execution.
globs: src/**/*.ts, lib/**/*.ts, native/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-pointer-lifecycle-pinning"
---

# Bun 1.2 Native C-FFI Pointer Lifecycle Pinning & GC Anchoring

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing Unanchored JavaScript Allocations as Zero-Copy Raw C-Pointers Across Async FFI Boundaries

## System Constraints
You are a Principal Systems Engineer enforcing strict Bun 1.2 Native C-FFI memory invariants. Mandate pointer anchoring patterns, explicit lifespan tracking via WeakRef/FinalizationRegistry or scope guards, and zero-allocation conversion boundaries. Strictly prohibit passing temporary Uint8Arrays or unpinned ArrayBuffers directly to asynchronous, background, or multi-threaded foreign function interfaces.

## Strict Guidelines
- Engineers MUST ALWAYS anchor JS-allocated memory (e.g., via `ptr(buffer)`) in an active lexical scope or dedicated `Set<ArrayBufferView>` until the foreign C function has definitively returned or signaled completion.
- Engineers MUST NOT pass transient `Uint8Array` allocations inline into non-blocking, worker-pool, or callback-driven C-FFI calls where the JSC GC can collect the underlying backing store mid-operation.
- Code SHOULD wrap asynchronous C operations in a lifecycle token or explicit RAII-style disposable pattern using `using` syntax to guarantee memory stays pinned for the full duration of native access.
- Services MUST explicitly call native memory free routines via dynamic binding symbols (`dlclose`, custom native deallocators) when managing foreign heap allocations rather than relying on uncoordinated JavaScriptCore GC.
- Components NEVER cast arbitrary JS numbers to raw pointer handles without boundary checks, validation of null pointers (`ptr === null` or `0n`), and alignment verification.

## Bad vs Good Implementations
### Async C-FFI Inlined Buffer Passing vs Explicit GC Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing `ptr(payload)` directly for a deferred or non-deterministic native operation leaves `payload` unreferenced in JS. JavaScriptCore's GC can collect the underlying `ArrayBuffer` during a concurrent sweep, leading to native read-after-free or memory corruption.
```typescript
import { cc, ptr } from "bun:ffi";

const { symbols } = cc({
  source: "./native/crypto.c",
  symbols: {
    process_payload_async: {
      args: ["ptr", "usize"],
      returns: "void",
    },
  },
});

export function submitTelemetry(data: Record<string, unknown>): void {
  // Anti-pattern: Encoded buffer is an ephemeral local variable
  const payload = new TextEncoder().encode(JSON.stringify(data));
  
  // JSC sweep can collect payload buffer while C background worker reads raw memory
  symbols.process_payload_async(ptr(payload), payload.byteLength);
}
```

#### Production Standard (Correct)
> **Standard**: The payload buffer is explicitly anchored in `activePins` (a root-reachable Set), keeping it immune from GC sweeps until the C-side completion callback is invoked and the buffer is deleted from the registry.
```typescript
import { cc, ptr, JSCallback } from "bun:ffi";

const activePins = new Set<Uint8Array>();

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

export async function submitTelemetry(data: Record<string, unknown>): Promise<void> {
  const payload = new TextEncoder().encode(JSON.stringify(data));
  
  // Anchor memory against JSC collector
  activePins.add(payload);

  return new Promise<void>((resolve, reject) => {
    const cb = new JSCallback(
      (status: number) => {
        // Release the anchor once native execution is complete
        activePins.delete(payload);
        cb.close();
        if (status === 0) resolve();
        else reject(new Error(`Native error code: ${status}`));
      },
      { args: ["int"], returns: "void" }
    );

    symbols.process_payload_async(ptr(payload), payload.byteLength, cb);
  });
}
```

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 C-FFI Pointer Lifecycle Pinning & GC Anchoring

Bun 1.2 Native C-FFI Pointer Lifecycle Pinning & GC Anchoring defines an industrial-grade behavioral standard for backend engineering. Enforces strict heap anchoring for typed arrays, buffers, and native pointers bridged to C dynamic libraries via `bun:ffi`. Prevents catastrophic use-after-free, memory corruption, and silent segmentation faults triggered by JavaScriptCore garbage collection sweeps during zero-copy asynchronous 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: Passing Unanchored JavaScript Allocations as Zero-Copy Raw C-Pointers Across Async FFI Boundaries 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 Unanchored JavaScript Allocations as Zero-Copy Raw C-Pointers Across Async FFI BoundariesCritical
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 anchor JS-allocated memory (e.g., via `ptr(buffer)`) in an active lexical scope or dedicated `Set<ArrayBufferView>` until the foreign C function has definitively returned or signaled completion.

Engineers MUST ALWAYS anchor JS-allocated memory (e.g., via `ptr(buffer)`) in an active lexical scope or dedicated `Set<ArrayBufferView>` until the foreign C function has definitively returned or signaled completion.

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 transient `Uint8Array` allocations inline into non-blocking, worker-pool, or callback-driven C-FFI calls where the JSC GC can collect the underlying backing store mid-operation.

Engineers MUST NOT pass transient `Uint8Array` allocations inline into non-blocking, worker-pool, or callback-driven C-FFI calls where the JSC GC can collect the underlying backing store mid-operation.

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 wrap asynchronous C operations in a lifecycle token or explicit RAII-style disposable pattern using `using` syntax to guarantee memory stays pinned for the full duration of native access.

Code SHOULD wrap asynchronous C operations in a lifecycle token or explicit RAII-style disposable pattern using `using` syntax to guarantee memory stays pinned for the full duration of native access.

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 explicitly call native memory free routines via dynamic binding symbols (`dlclose`, custom native deallocators) when managing foreign heap allocations rather than relying on uncoordinated JavaScriptCore GC.

Services MUST explicitly call native memory free routines via dynamic binding symbols (`dlclose`, custom native deallocators) when managing foreign heap allocations rather than relying on uncoordinated JavaScriptCore GC.

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 arbitrary JS numbers to raw pointer handles without boundary checks, validation of null pointers (`ptr === null` or `0n`), and alignment verification.

Components NEVER cast arbitrary JS numbers to raw pointer handles without boundary checks, validation of null pointers (`ptr === null` or `0n`), and alignment verification.

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 Pointer Lifecycle Pinning & GC Anchoring critical for AI coding assistants?

Enforces strict heap anchoring for typed arrays, buffers, and native pointers bridged to C dynamic libraries via `bun:ffi`. Prevents catastrophic use-after-free, memory corruption, and silent segmentation faults triggered by JavaScriptCore garbage collection sweeps during zero-copy asynchronous 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 (Passing Unanchored JavaScript Allocations as Zero-Copy Raw C-Pointers Across Async FFI Boundaries) 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