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

Bun 1.2 Native C-FFI Pointer Lifetime & Thread-Safe Worker Boundary

Enforces strict memory ownership, non-aliased pointer lifecycles, and isolated native resource pinning when executing foreign functions across Bun Worker threads. Prevents use-after-free conditions, double-frees, and v8/JSC GC-induced memory corruption during offloaded cryptographic or hardware-bound operations.

Prohibited Anti-Pattern: Transferring raw native pointers or retaining unpinned JS TypedArrays across asynchronous worker boundaries during native C-FFI execution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native C-FFI Pointer Lifetime & Thread-Safe Worker Boundary - Enforces strict memory ownership, non-aliased pointer lifecycles, and isolated native resource pinning when executing foreign functions across Bun Worker threads. Prevents use-after-free conditions, double-frees, and v8/JSC GC-induced memory corruption during offloaded cryptographic or hardware-bound operations.
globs: src/**/*.ts, workers/**/*.ts, lib/native/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-pointer-lifetime-worker-boundary"
---

# Bun 1.2 Native C-FFI Pointer Lifetime & Thread-Safe Worker Boundary

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Transferring raw native pointers or retaining unpinned JS TypedArrays across asynchronous worker boundaries during native C-FFI execution

## System Constraints
You are a Principal Systems Engineer enforcing strict native C-FFI memory safety and isolate separation under Bun 1.2. Mandate explicit ownership transfer, pointer pinning, deterministic deallocation, and shared-nothing worker boundaries to eliminate race conditions and segmentation faults.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate and execute `bun:ffi` bindings exclusively within the dedicated Worker isolate where the native memory is allocated and freed.
- Engineers MUST NOT transfer raw numeric pointers (`bun:ffi` `ptr` or integer representations) across `postMessage` channels, as memory spaces and lifetimes become unverifiable across JavaScript isolates.
- Code SHOULD transfer plain `ArrayBuffer` instances via transferable objects (`postMessage(msg, [transferable])`) to enforce single-owner byte boundaries without copying.
- Services MUST pin JavaScript TypedArrays using explicit reference anchors or dedicated native buffers until synchronous or asynchronous FFI invocations yield execution back to the runtime.
- Components NEVER call free/deallocation symbols on foreign memory from an isolate or worker thread different from the one that originated the allocation, unless the underlying native library explicitly documents thread-safe cross-thread deallocation.

## Bad vs Good Implementations
### Transferring Raw FFI Pointers Across Workers vs. Isolated Worker Execution with Transferable Buffers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a pointer derived via `ptr(rawData)` across thread/isolate boundaries creates an unsynchronized race condition. The Garbage Collector in the parent thread may reallocate or reclaim `rawData` while the worker processes the memory address, triggering catastrophic use-after-free or memory corruption.
```typescript
import { cc, ptr } from 'bun:ffi';

const lib = cc({
  source: './crypto.c',
  symbols: { heavy_encrypt: { args: ['ptr', 'usize'], returns: 'ptr' } },
});

// ANTI-PATTERN: Allocating in main thread and sending raw pointer to worker
const rawData = new Uint8Array([1, 2, 3, 4, 5]);
const rawPtr = ptr(rawData);

const worker = new Worker('./worker.ts');
// Leaks memory or causes use-after-free if rawData is GC'd before or during worker access
worker.postMessage({ pointer: rawPtr, length: rawData.byteLength });
```

#### Production Standard (Correct)
> **Standard**: FFI symbols and raw pointer abstractions remain tightly scoped to the worker thread. Input and output buffers are transferred across the isolate boundary via `ArrayBuffer` transfer lists, guaranteeing atomic ownership transfer, zero concurrent aliasing, and immunity to JavaScript GC use-after-free hazards.
```typescript
// worker.ts: Encapsulate native FFI bindings entirely within the worker isolate
import { cc, ptr, toArrayBuffer } from 'bun:ffi';

declare var self: Worker;

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

self.onmessage = (event: MessageEvent<ArrayBuffer>) => {
  const inputBuffer = event.data;
  const inputView = new Uint8Array(inputBuffer);
  const outputView = new Uint8Array(inputBuffer.byteLength);

  // Maintain explicit synchronous lifetime of typed arrays during the FFI call
  try {
    lib.symbols.heavy_encrypt(
      ptr(inputView),
      inputView.byteLength,
      ptr(outputView)
    );

    // Transfer ownership of the result buffer back to the host
    self.postMessage(outputView.buffer, [outputView.buffer]);
  } finally {
    // Buffers transferred or handled deterministically; zero-out references
  }
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Native C-FFI Pointer Lifetime & Thread-Safe Worker Boundary

Bun 1.2 Native C-FFI Pointer Lifetime & Thread-Safe Worker Boundary defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory ownership, non-aliased pointer lifecycles, and isolated native resource pinning when executing foreign functions across Bun Worker threads. Prevents use-after-free conditions, double-frees, and v8/JSC GC-induced memory corruption during offloaded cryptographic or hardware-bound operations. 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: Transferring raw native pointers or retaining unpinned JS TypedArrays across asynchronous worker boundaries during native C-FFI execution 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 DriftTransferring raw native pointers or retaining unpinned JS TypedArrays across asynchronous worker boundaries during native C-FFI executionCritical
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 instantiate and execute `bun

Engineers MUST ALWAYS instantiate and execute `bun:ffi` bindings exclusively within the dedicated Worker isolate where the native memory is allocated and freed.

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 transfer raw numeric pointers (`bun

Engineers MUST NOT transfer raw numeric pointers (`bun:ffi` `ptr` or integer representations) across `postMessage` channels, as memory spaces and lifetimes become unverifiable across JavaScript isolates.

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 transfer plain `ArrayBuffer` instances via transferable objects (`postMessage(msg, [transferable])`) to enforce single-owner byte boundaries without copying.

Code SHOULD transfer plain `ArrayBuffer` instances via transferable objects (`postMessage(msg, [transferable])`) to enforce single-owner byte boundaries without 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

Services MUST pin JavaScript TypedArrays using explicit reference anchors or dedicated native buffers until synchronous or asynchronous FFI invocations yield execution back to the runtime.

Services MUST pin JavaScript TypedArrays using explicit reference anchors or dedicated native buffers until synchronous or asynchronous FFI invocations yield execution back to the runtime.

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 call free/deallocation symbols on foreign memory from an isolate or worker thread different from the one that originated the allocation, unless the underlying native library explicitly documents thread-safe cross-thread deallocation.

Components NEVER call free/deallocation symbols on foreign memory from an isolate or worker thread different from the one that originated the allocation, unless the underlying native library explicitly documents thread-safe cross-thread 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.
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 Lifetime & Thread-Safe Worker Boundary critical for AI coding assistants?

Enforces strict memory ownership, non-aliased pointer lifecycles, and isolated native resource pinning when executing foreign functions across Bun Worker threads. Prevents use-after-free conditions, double-frees, and v8/JSC GC-induced memory corruption during offloaded cryptographic or hardware-bound operations. 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 (Transferring raw native pointers or retaining unpinned JS TypedArrays across asynchronous worker boundaries during native C-FFI execution) 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