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

Bun 1.2 Native Cluster Zero-Copy ArrayBuffer Transfer & Memory Detachment Guardrail

Enforces strict memory ownership transfer semantics when executing zero-copy ArrayBuffer IPC between Bun cluster primary and worker processes. Guarantees that transferred buffers are explicitly detached on the sending thread to prevent double-free, use-after-free, and segmentation faults across JavaScriptCore engine boundaries under high-throughput conditions.

Prohibited Anti-Pattern: Retaining or Mutating ArrayBuffer References Post-IPC Transfer Leading to JSC Host Panic

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native Cluster Zero-Copy ArrayBuffer Transfer & Memory Detachment Guardrail - Enforces strict memory ownership transfer semantics when executing zero-copy ArrayBuffer IPC between Bun cluster primary and worker processes. Guarantees that transferred buffers are explicitly detached on the sending thread to prevent double-free, use-after-free, and segmentation faults across JavaScriptCore engine boundaries under high-throughput conditions.
globs: src/**/*.{ts,js}, workers/**/*.{ts,js}, cluster/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-cluster-zerocopy-arraybuffer-invariant"
---

# Bun 1.2 Native Cluster Zero-Copy ArrayBuffer Transfer & Memory Detachment Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Retaining or Mutating ArrayBuffer References Post-IPC Transfer Leading to JSC Host Panic

## System Constraints
You are a Principal Systems and Backend Engineer enforcing strict memory safety invariants for Bun 1.2 native cluster IPC. Mandate that any zero-copy ArrayBuffer or TypedArray transferred across process boundaries via Bun's clustering or worker channels adheres to strict ownership transfer mechanics, verifying byteLength detachment and nullifying local references to eliminate use-after-free, shared-mutable-state corruption, and JSC panics.

## Strict Guidelines
- Engineers MUST ALWAYS pass the underlying `ArrayBuffer` within the transfer list parameter when executing `process.send()` or `worker.postMessage()` for zero-copy semantics.
- Engineers MUST NOT access, read, write, or cache any reference to an `ArrayBuffer` or its underlying `TypedArray` view after initiating transfer over the IPC channel.
- Services MUST verify `buffer.byteLength === 0` (detached state verification) immediately following transfer invocation to ensure the JSC native pointer was successfully yielded.
- Code SHOULD encapsulate zero-copy IPC payload dispatch within dedicated buffer ownership transfer envelopes that set sender references to `null` synchronously.
- Components NEVER share `SharedArrayBuffer` instances without explicit atomics synchronization, and MUST prefer zero-copy transferable `ArrayBuffer` isolation for distinct process boundaries.

## Bad vs Good Implementations
### Zero-Copy IPC ArrayBuffer Ownership Handover with Detachment Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to pass transferables causes structured-clone overhead or, in native zero-copy configurations, leaves an active reference to memory that has been transferred. Subsequent mutations or reads violate deterministic memory ownership and cause race conditions or VM panics.
```typescript
import cluster from 'node:cluster';

export function broadcastChunk(worker: cluster.Worker, payload: Uint8Array): void {
  // Anti-pattern: Payload sent without transfer list or sender reference revocation.
  // This copies memory unnecessarily or, if transfer is forced via low-level primitives,
  // leaves dangling references that trigger race conditions or JSC use-after-free.
  worker.send({ type: 'CHUNK', buffer: payload.buffer });

  // DANGEROUS: Sender retains reference and continues reading/mutating
  console.log(`Sent payload with byteLength: ${payload.buffer.byteLength}`);
  payload[0] = 0xFF; // Data race or segfault if worker accesses concurrently
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes the ArrayBuffer in the transferables array to revoke local ownership via JavaScriptCore native detachment. Asserts that `byteLength === 0` to verify detachment and nullifies local references, completely preventing double-free and use-after-free bugs.
```typescript
import cluster from 'node:cluster';

export interface TransferResult {
  detached: boolean;
  bytesTransferred: number;
}

export function transferChunkToWorker(
  worker: cluster.Worker,
  view: Uint8Array
): TransferResult {
  const targetBuffer = view.buffer;
  const initialSize = targetBuffer.byteLength;

  // Enforce zero-copy transfer list semantics
  // Bun 1.2 IPC supports passing transferable objects to yield native ownership
  worker.send({ type: 'CHUNK', payload: targetBuffer }, [targetBuffer]);

  // Mandatory Detachment Invariant Guard
  const isDetached = targetBuffer.byteLength === 0;
  if (!isDetached) {
    throw new Error('IPC_INVARIANT_VIOLATION: ArrayBuffer failed to detach upon IPC transfer.');
  }

  // Wipe view references to guarantee no use-after-free in current closure scope
  // @ts-expect-error explicit nullification to aid JSC garbage collection
  view = null;

  return {
    detached: true,
    bytesTransferred: initialSize
  };
}
```

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 Cluster Zero-Copy ArrayBuffer Transfer & Memory Detachment Guardrail

Bun 1.2 Native Cluster Zero-Copy ArrayBuffer Transfer & Memory Detachment Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory ownership transfer semantics when executing zero-copy ArrayBuffer IPC between Bun cluster primary and worker processes. Guarantees that transferred buffers are explicitly detached on the sending thread to prevent double-free, use-after-free, and segmentation faults across JavaScriptCore engine boundaries under high-throughput conditions. 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: Retaining or Mutating ArrayBuffer References Post-IPC Transfer Leading to JSC Host Panic 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 DriftRetaining or Mutating ArrayBuffer References Post-IPC Transfer Leading to JSC Host PanicCritical
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 pass the underlying `ArrayBuffer` within the transfer list parameter when executing `process.send()` or `worker.postMessage()` for zero-copy semantics.

Engineers MUST ALWAYS pass the underlying `ArrayBuffer` within the transfer list parameter when executing `process.send()` or `worker.postMessage()` for zero-copy semantics.

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 access, read, write, or cache any reference to an `ArrayBuffer` or its underlying `TypedArray` view after initiating transfer over the IPC channel.

Engineers MUST NOT access, read, write, or cache any reference to an `ArrayBuffer` or its underlying `TypedArray` view after initiating transfer over the IPC channel.

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

Services MUST verify `buffer.byteLength === 0` (detached state verification) immediately following transfer invocation to ensure the JSC native pointer was successfully yielded.

Services MUST verify `buffer.byteLength === 0` (detached state verification) immediately following transfer invocation to ensure the JSC native pointer was successfully yielded.

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 encapsulate zero-copy IPC payload dispatch within dedicated buffer ownership transfer envelopes that set sender references to `null` synchronously.

Code SHOULD encapsulate zero-copy IPC payload dispatch within dedicated buffer ownership transfer envelopes that set sender references to `null` synchronously.

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 share `SharedArrayBuffer` instances without explicit atomics synchronization, and MUST prefer zero-copy transferable `ArrayBuffer` isolation for distinct process boundaries.

Components NEVER share `SharedArrayBuffer` instances without explicit atomics synchronization, and MUST prefer zero-copy transferable `ArrayBuffer` isolation for distinct process boundaries.

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 Cluster Zero-Copy ArrayBuffer Transfer & Memory Detachment Guardrail critical for AI coding assistants?

Enforces strict memory ownership transfer semantics when executing zero-copy ArrayBuffer IPC between Bun cluster primary and worker processes. Guarantees that transferred buffers are explicitly detached on the sending thread to prevent double-free, use-after-free, and segmentation faults across JavaScriptCore engine boundaries under high-throughput conditions. 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 (Retaining or Mutating ArrayBuffer References Post-IPC Transfer Leading to JSC Host Panic) 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