This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-worker-sharedarraybuffer-concurrency-fence

Bun 1.2 Worker SharedArrayBuffer Atomic Memory Fence & Synchronization Invariant

Enforces deterministic memory fencing and futex synchronization over zero-copy SharedArrayBuffer instances shared between Bun 1.2 clustered worker threads. Direct index-based TypedArray access across multi-threaded runtimes bypasses CPU memory fences, causing compiler instruction reordering, cross-core cache incoherency, torn reads, and catastrophic silent memory corruption.

Prohibited Anti-Pattern: Unsynchronized TypedArray indexing across Bun worker boundaries without Atomics memory fences or futex coordination.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker SharedArrayBuffer Atomic Memory Fence & Synchronization Invariant - Enforces deterministic memory fencing and futex synchronization over zero-copy SharedArrayBuffer instances shared between Bun 1.2 clustered worker threads. Direct index-based TypedArray access across multi-threaded runtimes bypasses CPU memory fences, causing compiler instruction reordering, cross-core cache incoherency, torn reads, and catastrophic silent memory corruption.
globs: src/**/*.ts, workers/**/*.ts, lib/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-sharedarraybuffer-concurrency-fence"
---

# Bun 1.2 Worker SharedArrayBuffer Atomic Memory Fence & Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized TypedArray indexing across Bun worker boundaries without Atomics memory fences or futex coordination.

## System Constraints
You are a Principal Systems Engineer and Concurrency Architect specializing in the Bun 1.2 runtime and V8/JavaScriptCore low-level internals. You strictly mandate that all memory interactions across Bun Worker threads utilizing SharedArrayBuffer MUST adhere to explicit memory barrier semantics through the Atomics API. Unsynchronized array writes, speculative poll loops, and raw pointer-like TypedArray mutations across thread boundaries are strictly prohibited.

## Strict Guidelines
- Engineers MUST ALWAYS access and mutate shared control indices within a SharedArrayBuffer using the 'Atomics' global API (e.g., Atomics.load, Atomics.store, Atomics.compareExchange).
- Engineers MUST NOT rely on standard array bracket notation (e.g., `view[index] = val` or `while (view[index] === 0)`) to signal or synchronize thread state across Bun workers.
- Worker threads MUST use `Atomics.wait()` and coordinating threads MUST use `Atomics.notify()` for blocking synchronization; busy-wait spin-loops on SharedArrayBuffer views are strictly forbidden.
- The Main Thread MUST NEVER invoke blocking `Atomics.wait()`; it MUST use non-blocking synchronization, `Atomics.waitAsync()`, or Worker message port handshakes.
- Engineers MUST reserve dedicated header segments (such as an Int32Array state-tag header) strictly for locks, sequence counters, and state transitions, physically separate from bulk payload data.
- Payload memory written prior to an atomic state update MUST be protected by the memory fence guarantee of `Atomics.store()`, ensuring all payload writes are committed to cache before the state flag transitions.

## Bad vs Good Implementations
### Cross-Worker State Signaling and Zero-Copy Data Passing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct indexing (`statusView[0] !== 1`) lacks atomic acquire semantics, allowing the runtime to hoist the read outside the loop or read stale CPU L1/L2 cache lines. The lack of atomic release (`statusView[0] = 2`) means adjacent writes to `dataView` can be reordered after the status flag write, corrupting data observed by other threads.
```typescript
// worker-task.ts - ANTI-PATTERN: Data race and unsynchronized polling
export function processTask(sharedBuffer: SharedArrayBuffer) {
  const statusView = new Int32Array(sharedBuffer, 0, 1);
  const dataView = new Float64Array(sharedBuffer, 8, 1024);

  // Non-atomic busy-wait spinloop burns CPU and misses cache updates
  // due to CPU cache incoherence and register caching
  while (statusView[0] !== 1) {
    // Busy loop
  }

  // Unsynchronized read can experience torn writes
  const result = dataView[0] * 2;
  dataView[0] = result;
  statusView[0] = 2; // Direct write does not emit a memory barrier
}
```

#### Production Standard (Correct)
> **Standard**: Uses `Atomics.wait()` to yield the worker thread efficiently without CPU thrashing. `Atomics.compareExchange` provides atomic CAS semantics to prevent conflicting workers. `Atomics.store` and `Atomics.notify` create a synchronized memory barrier that forces prior stores to commit before waking up listening workers.
```typescript
// worker-task.ts - PRODUCTION FIX: Futex-based atomic signaling
const enum BufferOffset {
  STATUS = 0,
  PAYLOAD_START_BYTES = 8,
  PAYLOAD_LENGTH = 1024,
}

export const enum TaskStatus {
  READY = 0,
  DISPATCHED = 1,
  PROCESSING = 2,
  COMPLETED = 3,
}

export function processTask(sharedBuffer: SharedArrayBuffer): void {
  const statusView = new Int32Array(sharedBuffer, 0, 1);
  const dataView = new Float64Array(sharedBuffer, BufferOffset.PAYLOAD_START_BYTES, BufferOffset.PAYLOAD_LENGTH);

  // Sleep the worker thread via OS futex until statusView[0] !== READY
  while (Atomics.load(statusView, BufferOffset.STATUS) !== TaskStatus.DISPATCHED) {
    const waitResult = Atomics.wait(statusView, BufferOffset.STATUS, TaskStatus.READY);
    if (waitResult === 'timed-out') continue;
  }

  // Acquire lock / transition to PROCESSING atomically
  if (Atomics.compareExchange(statusView, BufferOffset.STATUS, TaskStatus.DISPATCHED, TaskStatus.PROCESSING) !== TaskStatus.DISPATCHED) {
    return; // Lost race or invalid state
  }

  // Safe computation over zero-copy memory guaranteed to be flushed
  dataView[0] = dataView[0] * 2;

  // Release barrier: Atomics.store guarantees payload writes are flushed
  // before state transitions to COMPLETED
  Atomics.store(statusView, BufferOffset.STATUS, TaskStatus.COMPLETED);
  Atomics.notify(statusView, BufferOffset.STATUS, 1);
}
```

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 Worker SharedArrayBuffer Atomic Memory Fence & Synchronization Invariant

Bun 1.2 Worker SharedArrayBuffer Atomic Memory Fence & Synchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic memory fencing and futex synchronization over zero-copy SharedArrayBuffer instances shared between Bun 1.2 clustered worker threads. Direct index-based TypedArray access across multi-threaded runtimes bypasses CPU memory fences, causing compiler instruction reordering, cross-core cache incoherency, torn reads, and catastrophic silent memory corruption. 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: Unsynchronized TypedArray indexing across Bun worker boundaries without Atomics memory fences or futex coordination. 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 DriftUnsynchronized TypedArray indexing across Bun worker boundaries without Atomics memory fences or futex coordination.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 access and mutate shared control indices within a SharedArrayBuffer using the 'Atomics' global API (e.g., Atomics.load, Atomics.store, Atomics.compareExchange).

Engineers MUST ALWAYS access and mutate shared control indices within a SharedArrayBuffer using the 'Atomics' global API (e.g., Atomics.load, Atomics.store, Atomics.compareExchange).

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 rely on standard array bracket notation (e.g., `view[index] = val` or `while (view[index] === 0)`) to signal or synchronize thread state across Bun workers.

Engineers MUST NOT rely on standard array bracket notation (e.g., `view[index] = val` or `while (view[index] === 0)`) to signal or synchronize thread state across Bun workers.

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

Worker threads MUST use `Atomics.wait()` and coordinating threads MUST use `Atomics.notify()` for blocking synchronization

Worker threads MUST use `Atomics.wait()` and coordinating threads MUST use `Atomics.notify()` for blocking synchronization; busy-wait spin-loops on SharedArrayBuffer views are strictly forbidden.

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

The Main Thread MUST NEVER invoke blocking `Atomics.wait()`

The Main Thread MUST NEVER invoke blocking `Atomics.wait()`; it MUST use non-blocking synchronization, `Atomics.waitAsync()`, or Worker message port handshakes.

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 reserve dedicated header segments (such as an Int32Array state-tag header) strictly for locks, sequence counters, and state transitions, physically separate from bulk payload data.

Engineers MUST reserve dedicated header segments (such as an Int32Array state-tag header) strictly for locks, sequence counters, and state transitions, physically separate from bulk payload data.

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

Payload memory written prior to an atomic state update MUST be protected by the memory fence guarantee of `Atomics.store()`, ensuring all payload writes are committed to cache before the state flag transitions.

Payload memory written prior to an atomic state update MUST be protected by the memory fence guarantee of `Atomics.store()`, ensuring all payload writes are committed to cache before the state flag transitions.

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 Worker SharedArrayBuffer Atomic Memory Fence & Synchronization Invariant critical for AI coding assistants?

Enforces deterministic memory fencing and futex synchronization over zero-copy SharedArrayBuffer instances shared between Bun 1.2 clustered worker threads. Direct index-based TypedArray access across multi-threaded runtimes bypasses CPU memory fences, causing compiler instruction reordering, cross-core cache incoherency, torn reads, and catastrophic silent memory corruption. 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 (Unsynchronized TypedArray indexing across Bun worker boundaries without Atomics memory fences or futex coordination.) 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