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

Bun 1.2 FFI Zero-Copy Pointer Alignment and Lifetime Pinning Guardrail

Enforces strict memory boundary, byte alignment, and GC lifetime anchoring when marshalling zero-copy typed arrays to native C-ABI and SIMD routines via Bun 1.2 FFI. Prevents silent memory corruption, microarchitectural page-boundary faults, and SIGSEGV/SIGBUS crashes caused by unaligned vector loads or premature JavaScriptCore garbage collection.

Prohibited Anti-Pattern: Passing unaligned TypedArray views or unanchored buffers directly to native SIMD/C functions via bun:ffi.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 FFI Zero-Copy Pointer Alignment and Lifetime Pinning Guardrail - Enforces strict memory boundary, byte alignment, and GC lifetime anchoring when marshalling zero-copy typed arrays to native C-ABI and SIMD routines via Bun 1.2 FFI. Prevents silent memory corruption, microarchitectural page-boundary faults, and SIGSEGV/SIGBUS crashes caused by unaligned vector loads or premature JavaScriptCore garbage collection.
globs: src/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-1-2-ffi-zerocopy-pointer-alignment-guardrail"
---

# Bun 1.2 FFI Zero-Copy Pointer Alignment and Lifetime Pinning Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing unaligned TypedArray views or unanchored buffers directly to native SIMD/C functions via bun:ffi.

## System Constraints
You are a Principal Engineer enforcing the Bun 1.2 FFI Zero-Copy Pointer Alignment Guardrail. Native FFI calls involving SIMD (SSE, AVX2, AVX-512, ARM NEON) or C-structs require strict power-of-two pointer alignment and explicit GC anchoring. You must prevent unaligned memory access, verify TypedArray byte offsets, and ensure backing buffers cannot be garbage collected or relocated during native invocation.

## Strict Guidelines
- Engineers MUST ALWAYS verify that native pointers derived from `ptr()` satisfy architecture-specific alignment (e.g., 16-byte for NEON/SSE, 32-byte for AVX2, 64-byte for AVX-512) before passing them to native symbols.
- Engineers MUST NOT pass sliced TypedArray views (`subarray`) directly to native code without explicitly verifying that `typedArray.byteOffset` maintains required struct and vector alignment.
- Engineers MUST maintain an active reference to the underlying `ArrayBuffer` in JavaScript scope across the entirety of the synchronous or asynchronous native call to prevent JavaScriptCore GC reclamation or heap compaction.
- Code SHOULD allocate aligned buffers using an over-allocated memory pool or aligned allocation wrapper when zero-copy SIMD processing is required.
- Services MUST fail fast by throwing an explicit `RangeError` or `TypeError` before calling native symbols if `BigInt(ptr(buffer)) & (ALIGNMENT - 1n) !== 0n`.
- Components NEVER assume JavaScriptCore's default `TypedArray` allocation is aligned beyond standard object allocation boundaries (typically 8 bytes).

## Bad vs Good Implementations
### Unchecked Subarray Pointer Passed to AVX2 Native Function

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing an arbitrary `subarray` offset to native AVX2 instructions (e.g., `_mm256_load_si256`) causes CPU hardware faults (`SIGBUS` or `SIGSEGV`) when traversing page boundaries unaligned. Furthermore, dynamic buffers without explicit variable retention risk premature deallocation during async processing.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

const lib = dlopen("libvector.so", {
  process_avx2: {
    args: [FFIType.ptr, FFIType.u64],
    returns: FFIType.void,
  },
});

export function executeVectorOp(input: Uint8Array, offset: number) {
  // Subarray introduces an arbitrary byteOffset that breaks 32-byte AVX2 alignment
  const slice = input.subarray(offset);
  
  // Passing raw pointer without alignment assertion or GC lifetime pin
  lib.symbols.process_avx2(ptr(slice), slice.byteLength);
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation constructs a correctly aligned view by computing alignment padding against the physical pointer address. It performs a bitwise guard check (`address & ALIGNMENT_MASK === 0n`) to fail safely before entering native execution, and explicitly references `alignedView.buffer` to pin the allocation in JSC memory.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

const AVX2_ALIGNMENT_BYTES = 32n;
const ALIGNMENT_MASK = AVX2_ALIGNMENT_BYTES - 1n;

const lib = dlopen("libvector.so", {
  process_avx2: {
    args: [FFIType.ptr, FFIType.u64],
    returns: FFIType.void,
  },
});

export function createAlignedBuffer(byteLength: number, alignment = 32): Uint8Array {
  const buffer = new ArrayBuffer(byteLength + alignment);
  const basePtr = BigInt(ptr(buffer));
  const offset = Number((BigInt(alignment) - (basePtr % BigInt(alignment))) % BigInt(alignment));
  return new Uint8Array(buffer, offset, byteLength);
}

export function executeVectorOp(alignedView: Uint8Array): void {
  const address = BigInt(ptr(alignedView));
  
  if ((address & ALIGNMENT_MASK) !== 0n) {
    throw new TypeError(
      `FFI Alignment Fault: Pointer 0x${address.toString(16)} is not ${AVX2_ALIGNMENT_BYTES}-byte aligned.`
    );
  }

  try {
    lib.symbols.process_avx2(address, alignedView.byteLength);
  } finally {
    // Pin backing store: explicit reference ensures JSC GC cannot collect the buffer
    void alignedView.buffer;
  }
}
```

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 FFI Zero-Copy Pointer Alignment and Lifetime Pinning Guardrail

Bun 1.2 FFI Zero-Copy Pointer Alignment and Lifetime Pinning Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory boundary, byte alignment, and GC lifetime anchoring when marshalling zero-copy typed arrays to native C-ABI and SIMD routines via Bun 1.2 FFI. Prevents silent memory corruption, microarchitectural page-boundary faults, and SIGSEGV/SIGBUS crashes caused by unaligned vector loads or premature JavaScriptCore garbage collection. 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 unaligned TypedArray views or unanchored buffers directly to native SIMD/C functions via bun:ffi. 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 unaligned TypedArray views or unanchored buffers directly to native SIMD/C functions via bun:ffi.Critical
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 verify that native pointers derived from `ptr()` satisfy architecture-specific alignment (e.g., 16-byte for NEON/SSE, 32-byte for AVX2, 64-byte for AVX-512) before passing them to native symbols.

Engineers MUST ALWAYS verify that native pointers derived from `ptr()` satisfy architecture-specific alignment (e.g., 16-byte for NEON/SSE, 32-byte for AVX2, 64-byte for AVX-512) before passing them to native symbols.

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 sliced TypedArray views (`subarray`) directly to native code without explicitly verifying that `typedArray.byteOffset` maintains required struct and vector alignment.

Engineers MUST NOT pass sliced TypedArray views (`subarray`) directly to native code without explicitly verifying that `typedArray.byteOffset` maintains required struct and vector alignment.

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 maintain an active reference to the underlying `ArrayBuffer` in JavaScript scope across the entirety of the synchronous or asynchronous native call to prevent JavaScriptCore GC reclamation or heap compaction.

Engineers MUST maintain an active reference to the underlying `ArrayBuffer` in JavaScript scope across the entirety of the synchronous or asynchronous native call to prevent JavaScriptCore GC reclamation or heap compaction.

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 SHOULD allocate aligned buffers using an over-allocated memory pool or aligned allocation wrapper when zero-copy SIMD processing is required.

Code SHOULD allocate aligned buffers using an over-allocated memory pool or aligned allocation wrapper when zero-copy SIMD processing 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.
5

Services MUST fail fast by throwing an explicit `RangeError` or `TypeError` before calling native symbols if `BigInt(ptr(buffer)) & (ALIGNMENT - 1n) !== 0n`.

Services MUST fail fast by throwing an explicit `RangeError` or `TypeError` before calling native symbols if `BigInt(ptr(buffer)) & (ALIGNMENT - 1n) !== 0n`.

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 assume JavaScriptCore's default `TypedArray` allocation is aligned beyond standard object allocation boundaries (typically 8 bytes).

Components NEVER assume JavaScriptCore's default `TypedArray` allocation is aligned beyond standard object allocation boundaries (typically 8 bytes).

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 FFI Zero-Copy Pointer Alignment and Lifetime Pinning Guardrail critical for AI coding assistants?

Enforces strict memory boundary, byte alignment, and GC lifetime anchoring when marshalling zero-copy typed arrays to native C-ABI and SIMD routines via Bun 1.2 FFI. Prevents silent memory corruption, microarchitectural page-boundary faults, and SIGSEGV/SIGBUS crashes caused by unaligned vector loads or premature JavaScriptCore garbage collection. 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 unaligned TypedArray views or unanchored buffers directly to native SIMD/C functions via bun:ffi.) 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