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

Bun 1.2 Zero-Copy ArrayBuffer Transfer Isolation Invariants

Enforces strict detachment verification and lifecycle ownership transfers when passing ArrayBuffers across Bun 1.2 multi-threaded worker pools via postMessage. Prevents use-after-free, concurrent mutation race conditions, and race-induced memory corruption by asserting explicit buffer neutering on senders and validation of transfer ownership on receivers.

Prohibited Anti-Pattern: Accessing Detached ArrayBuffers or Sharing Non-Transferable References Across Worker Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Zero-Copy ArrayBuffer Transfer Isolation Invariants - Enforces strict detachment verification and lifecycle ownership transfers when passing ArrayBuffers across Bun 1.2 multi-threaded worker pools via postMessage. Prevents use-after-free, concurrent mutation race conditions, and race-induced memory corruption by asserting explicit buffer neutering on senders and validation of transfer ownership on receivers.
globs: src/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-zero-copy-buffer-transfer-isolation"
---

# Bun 1.2 Zero-Copy ArrayBuffer Transfer Isolation Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Accessing Detached ArrayBuffers or Sharing Non-Transferable References Across Worker Boundaries

## System Constraints
You are a Principal Systems Engineer enforcing Bun 1.2 Zero-Copy ArrayBuffer Transfer Isolation Invariants. In Bun 1.2, passing an ArrayBuffer via Worker.postMessage transferList neuters (detaches) the underlying memory on the sending thread. You must mandate strict post-transfer reference invalidation, prohibit retained TypedArray views on neutered buffers, forbid transferring SharedArrayBuffer in zero-copy transfer semantics, and enforce explicit `byteLength === 0` validation or structural clone isolation.

## Strict Guidelines
- Engineers MUST ALWAYS pass the exact underlying `ArrayBuffer` in the `transferList` parameter of `worker.postMessage(message, [buffer])` when zero-copy semantics are required.
- Engineers MUST immediately nullify, reassign, or discard all references and TypedArray views pointing to a transferred ArrayBuffer in the sending context to prevent accessing detached memory.
- Engineers MUST NOT attempt to read, write, or query TypedArray views derived from an ArrayBuffer after it has been included in a transfer list; checks MUST verify `buffer.detached` (or `buffer.byteLength === 0`) before subsequent use.
- Services MUST explicitly validate that incoming Worker payloads contain valid, attached ArrayBuffers with `byteLength > 0` before instantiating TypedArray or DataView structures.
- Engineers MUST NEVER include `SharedArrayBuffer` in the `transferList` array, as SharedArrayBuffers cannot be detached and violate single-owner isolation invariants.
- Worker boundaries MUST encapsulate transfer logic within a transactional boundary: if message serialization or dispatch fails, the memory buffer state MUST be predictably reclaimed or regenerated.

## Bad vs Good Implementations
### Zero-Copy ArrayBuffer Transfer with Explicit Sender Detachment and Ownership Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing `buffer` in the transfer list detaches its memory in the sending thread. Retaining and accessing `view` triggers detached buffer exceptions or silent no-ops, leading to severe use-after-transfer race conditions or runtime crashes.
```typescript
import { Worker } from 'bun';

const worker = new Worker(new URL('./worker.ts', import.meta.url).href);
const buffer = new ArrayBuffer(1024 * 1024);
const view = new Uint8Array(buffer);
view[0] = 42;

// ANTI-PATTERN: Transferred in transferList, but sender retains and reuses 'view' and 'buffer'
worker.postMessage({ type: 'PROCESS_CHUNK', payload: buffer }, [buffer]);

// Dangerous access: buffer is detached in Bun 1.2! view.byteLength is 0
console.log(view[0]); // Returns undefined or throws in strict contexts
view[1] = 10;         // Throws TypeError: Cannot perform %TypedArray%.prototype.set on a detached ArrayBuffer
```

#### Production Standard (Correct)
> **Standard**: The sending context nullifies internal references to both the ArrayBuffer and associated TypedArray views prior to or immediately upon transfer. An explicit detachment check guarantees memory ownership was transferred cleanly without leaving dangling pointers in the calling thread.
```typescript
import { Worker } from 'bun';

interface TransferContext {
  rawBuffer: ArrayBuffer | null;
  view: Uint8Array | null;
}

const worker = new Worker(new URL('./worker.ts', import.meta.url).href);
const context: TransferContext = {
  rawBuffer: new ArrayBuffer(1024 * 1024),
  view: null
};

context.view = new Uint8Array(context.rawBuffer);
context.view[0] = 42;

// Secure transfer: Extract target buffer, transfer, and deterministically clear references
const transferable = context.rawBuffer;
context.rawBuffer = null;
context.view = null;

worker.postMessage({ type: 'PROCESS_CHUNK', payload: transferable }, [transferable]);

// Verified invariant: Old references are explicitly purged
if (transferable.byteLength !== 0 && !('detached' in transferable && transferable.detached)) {
  throw new Error('Invariant violation: ArrayBuffer was not properly detached post-transfer');
}
```

### Worker Ingestion Guardrail: Safe Receipt and Verification of Transferred Buffers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The worker blindly casts the incoming payload to a TypedArray without verifying that the transferred object is an instantiated, attached ArrayBuffer with non-zero length, failing to guard against empty or neutered buffers sent erroneously.
```typescript
// worker.ts
declare const self: Worker;

self.onmessage = (event: MessageEvent) => {
  const { payload } = event.data;
  // ANTI-PATTERN: Blindly assuming payload is an attached, valid ArrayBuffer
  const view = new Uint8Array(payload);
  // If payload is already detached or malformed, operations silently corrupt or crash
  for (let i = 0; i < view.length; i++) {
    view[i] = view[i] ^ 0xFF;
  }
};
```

#### Production Standard (Correct)
> **Standard**: The worker strictly enforces runtime validation on the incoming message payload, verifying that the transferred object is an instance of ArrayBuffer and contains non-zero byteLength, ensuring genuine ownership and avoiding detached view initialization.
```typescript
// worker.ts
declare const self: Worker;

interface WorkerEnvelope {
  type: string;
  payload: unknown;
}

self.onmessage = (event: MessageEvent<WorkerEnvelope>) => {
  const { type, payload } = event.data;

  if (type !== 'PROCESS_CHUNK') return;

  // Guardrail: Validate invariant that payload is an intact, non-detached ArrayBuffer
  if (!(payload instanceof ArrayBuffer)) {
    throw new TypeError('Worker Protocol Error: Expected payload to be an ArrayBuffer');
  }

  // In Bun 1.2, detached buffers have byteLength === 0
  if (payload.byteLength === 0) {
    throw new Error('Worker Isolation Error: Received an empty or detached ArrayBuffer');
  }

  const view = new Uint8Array(payload);
  // Safe single-threaded local processing
  for (let i = 0; i < view.length; i++) {
    view[i] = view[i] ^ 0xFF;
  }
};
```

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 Zero-Copy ArrayBuffer Transfer Isolation Invariants

Bun 1.2 Zero-Copy ArrayBuffer Transfer Isolation Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces strict detachment verification and lifecycle ownership transfers when passing ArrayBuffers across Bun 1.2 multi-threaded worker pools via postMessage. Prevents use-after-free, concurrent mutation race conditions, and race-induced memory corruption by asserting explicit buffer neutering on senders and validation of transfer ownership on receivers. 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: Accessing Detached ArrayBuffers or Sharing Non-Transferable References Across 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 DriftAccessing Detached ArrayBuffers or Sharing Non-Transferable References Across 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 pass the exact underlying `ArrayBuffer` in the `transferList` parameter of `worker.postMessage(message, [buffer])` when zero-copy semantics are required.

Engineers MUST ALWAYS pass the exact underlying `ArrayBuffer` in the `transferList` parameter of `worker.postMessage(message, [buffer])` when zero-copy semantics are 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.
2

Engineers MUST immediately nullify, reassign, or discard all references and TypedArray views pointing to a transferred ArrayBuffer in the sending context to prevent accessing detached memory.

Engineers MUST immediately nullify, reassign, or discard all references and TypedArray views pointing to a transferred ArrayBuffer in the sending context to prevent accessing detached memory.

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 NOT attempt to read, write, or query TypedArray views derived from an ArrayBuffer after it has been included in a transfer list

Engineers MUST NOT attempt to read, write, or query TypedArray views derived from an ArrayBuffer after it has been included in a transfer list; checks MUST verify `buffer.detached` (or `buffer.byteLength === 0`) before subsequent use.

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 validate that incoming Worker payloads contain valid, attached ArrayBuffers with `byteLength > 0` before instantiating TypedArray or DataView structures.

Services MUST explicitly validate that incoming Worker payloads contain valid, attached ArrayBuffers with `byteLength > 0` before instantiating TypedArray or DataView structures.

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

Engineers MUST NEVER include `SharedArrayBuffer` in the `transferList` array, as SharedArrayBuffers cannot be detached and violate single-owner isolation invariants.

Engineers MUST NEVER include `SharedArrayBuffer` in the `transferList` array, as SharedArrayBuffers cannot be detached and violate single-owner isolation invariants.

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

Worker boundaries MUST encapsulate transfer logic within a transactional boundary

Worker boundaries MUST encapsulate transfer logic within a transactional boundary: if message serialization or dispatch fails, the memory buffer state MUST be predictably reclaimed or regenerated.

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 ArrayBuffer Transfer Isolation Invariants critical for AI coding assistants?

Enforces strict detachment verification and lifecycle ownership transfers when passing ArrayBuffers across Bun 1.2 multi-threaded worker pools via postMessage. Prevents use-after-free, concurrent mutation race conditions, and race-induced memory corruption by asserting explicit buffer neutering on senders and validation of transfer ownership on receivers. 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 (Accessing Detached ArrayBuffers or Sharing Non-Transferable References Across 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