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

Bun 1.2 Zero-Copy FFI & Native Worker Thread Memory Safety Invariant

Enforces strict memory ownership, pointer lifecycle validation, and deterministic buffer pooling when passing high-throughput analytical buffers across Bun 1.2 C-ABI FFI and native Worker thread boundaries. Prevents silent heap corruption, use-after-free, and race conditions resulting from JavaScript garbage collection preempting native memory references.

Prohibited Anti-Pattern: Unpinned Pointer Passing & Shared Mutable ArrayBuffer Transfer Across FFI Worker Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy FFI & Native Worker Thread Memory Safety Invariant - Enforces strict memory ownership, pointer lifecycle validation, and deterministic buffer pooling when passing high-throughput analytical buffers across Bun 1.2 C-ABI FFI and native Worker thread boundaries. Prevents silent heap corruption, use-after-free, and race conditions resulting from JavaScript garbage collection preempting native memory references.
globs: src/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-ffi-worker-isolation-guardrail"
---

# Bun 1.2 Zero-Copy FFI & Native Worker Thread Memory Safety Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unpinned Pointer Passing & Shared Mutable ArrayBuffer Transfer Across FFI Worker Boundaries

## System Constraints
You are a Principal Systems Architect enforcing strict Bun 1.2 C-ABI Foreign Function Interface (FFI) memory safety and native Worker thread isolation. Zero-copy operations must strictly delineate between V8/JSC-managed heap buffers and non-moving raw native memory. Never allow a GC-managed Uint8Array/ArrayBuffer pointer to outlive its synchronous call frame, and never share mutable raw pointers across Worker threads without SharedArrayBuffer and explicit synchronization primitives.

## Strict Guidelines
- Engineers MUST ALWAYS retain an explicit reference to the underlying Buffer/TypedArray in JavaScript scope for the entire duration of an asynchronous or non-blocking FFI operation to prevent JavaScriptCore GC reclamation.
- Engineers MUST NOT pass raw pointers obtained via `ptr()` across Worker boundaries via `postMessage()`; workers MUST receive either detached ArrayBuffers via transfer lists or isolated SharedArrayBuffer instances with Atomics synchronization.
- Code MUST use Bun's native `toArrayBuffer(ptr, byteOffset, byteLength)` with deterministic byte boundaries and explicitly clone or detach the buffer when cross-thread isolation is required.
- Services MUST implement explicit lifecycles (e.g., using `using` syntax via `Symbol.dispose` / `Symbol.asyncDispose`) for native memory allocations executed through FFI symbols like `malloc` and `free`.
- Components NEVER cast volatile FFI return pointers directly to JavaScript typed arrays without validating non-null pointer status and alignment restrictions.

## Bad vs Good Implementations
### Unsafe FFI Pointer Forwarding vs. Deterministic Pinned Buffer Lifecycle with Worker Transfer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing raw memory addresses directly to worker threads bypasses thread isolation invariants. Furthermore, Bun's GC can collect or relocate the underlying TypedArray backing buffer while the C routine or downstream Worker is reading it, causing use-after-free or memory corruption.
```typescript
import { cc, ptr } from "bun:ffi";

const lib = cc({
  source: "./analytics.c",
  symbols: {
    process_stream: {
      args: ["ptr", "usize"],
      returns: "void",
    },
  },
});

export function dispatchToWorker(data: Uint8Array, worker: Worker) {
  // Anti-Pattern: Passing raw FFI pointer across Worker boundary.
  // The underlying memory is managed by JSC and can be collected or compacted,
  // causing a dangling pointer and SIGSEGV or cross-thread heap corruption.
  const rawPtr = ptr(data);
  lib.symbols.process_stream(rawPtr, data.byteLength);
  worker.postMessage({ memoryAddress: rawPtr, length: data.byteLength });
}
```

#### Production Standard (Correct)
> **Standard**: The good example encapsulates memory within an explicit lifecycle manager using TypeScript 5.2+ Explicit Resource Management. The synchronous FFI call operates on a pinned Uint8Array, and memory is transferred to the Worker via zero-copy ArrayBuffer transfer list, completely detaching it from the caller thread and guaranteeing memory safety without raw pointer sharing.
```typescript
import { cc, ptr } from "bun:ffi";

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

export class SafeFFIBuffer implements Disposable {
  private buffer: ArrayBuffer | null;
  readonly byteLength: number;

  constructor(size: number) {
    this.buffer = new ArrayBuffer(size);
    this.byteLength = size;
  }

  executeAndTransfer(worker: Worker): void {
    if (!this.buffer) throw new Error("Buffer already disposed or transferred");
    
    // Pinned reference guarantees GC cannot reclaim the memory during FFI execution
    const view = new Uint8Array(this.buffer);
    process_stream(ptr(view), this.byteLength);

    // Safely transfer ownership to the native Worker without copying memory
    const transferred = this.buffer;
    this.buffer = null;
    worker.postMessage({ payload: transferred }, [transferred]);
  }

  [Symbol.dispose](): void {
    this.buffer = null;
  }
}
```

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 Zero-Copy FFI & Native Worker Thread Memory Safety Invariant

Bun 1.2 Zero-Copy FFI & Native Worker Thread Memory Safety Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory ownership, pointer lifecycle validation, and deterministic buffer pooling when passing high-throughput analytical buffers across Bun 1.2 C-ABI FFI and native Worker thread boundaries. Prevents silent heap corruption, use-after-free, and race conditions resulting from JavaScript garbage collection preempting native memory references. 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: Unpinned Pointer Passing & Shared Mutable ArrayBuffer Transfer Across FFI Worker 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 DriftUnpinned Pointer Passing & Shared Mutable ArrayBuffer Transfer Across FFI Worker 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 retain an explicit reference to the underlying Buffer/TypedArray in JavaScript scope for the entire duration of an asynchronous or non-blocking FFI operation to prevent JavaScriptCore GC reclamation.

Engineers MUST ALWAYS retain an explicit reference to the underlying Buffer/TypedArray in JavaScript scope for the entire duration of an asynchronous or non-blocking FFI operation to prevent JavaScriptCore GC reclamation.

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 raw pointers obtained via `ptr()` across Worker boundaries via `postMessage()`

Engineers MUST NOT pass raw pointers obtained via `ptr()` across Worker boundaries via `postMessage()`; workers MUST receive either detached ArrayBuffers via transfer lists or isolated SharedArrayBuffer instances with Atomics synchronization.

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's native `toArrayBuffer(ptr, byteOffset, byteLength)` with deterministic byte boundaries and explicitly clone or detach the buffer when cross-thread isolation is required.

Code MUST use Bun's native `toArrayBuffer(ptr, byteOffset, byteLength)` with deterministic byte boundaries and explicitly clone or detach the buffer when cross-thread isolation is required.

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 implement explicit lifecycles (e.g., using `using` syntax via `Symbol.dispose` / `Symbol.asyncDispose`) for native memory allocations executed through FFI symbols like `malloc` and `free`.

Services MUST implement explicit lifecycles (e.g., using `using` syntax via `Symbol.dispose` / `Symbol.asyncDispose`) for native memory allocations executed through FFI symbols like `malloc` and `free`.

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 volatile FFI return pointers directly to JavaScript typed arrays without validating non-null pointer status and alignment restrictions.

Components NEVER cast volatile FFI return pointers directly to JavaScript typed arrays without validating non-null pointer status and alignment restrictions.

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 FFI & Native Worker Thread Memory Safety Invariant critical for AI coding assistants?

Enforces strict memory ownership, pointer lifecycle validation, and deterministic buffer pooling when passing high-throughput analytical buffers across Bun 1.2 C-ABI FFI and native Worker thread boundaries. Prevents silent heap corruption, use-after-free, and race conditions resulting from JavaScript garbage collection preempting native memory references. 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 (Unpinned Pointer Passing & Shared Mutable ArrayBuffer Transfer Across FFI Worker 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