This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: coop-atomics-sharedarraybuffer-fencing

Cross-Origin Isolation and Atomics Fencing for SharedArrayBuffer Concurrency

Mandates strict cross-origin isolation headers (COOP/COEP) to safely instantiate SharedArrayBuffer without Spectre exposure, combined with explicit Atomics memory fencing between main-thread rendering pipelines and WebAssembly worker pools. Forbids un-synchronized shared memory mutation and illegal main-thread Atomics.wait calls to prevent browser freezing and torn reads.

Prohibited Anti-Pattern: Unsynchronized SharedArrayBuffer Access and Main-Thread Blocking Atomics Under Insecure Origin Isolation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Cross-Origin Isolation and Atomics Fencing for SharedArrayBuffer Concurrency - Mandates strict cross-origin isolation headers (COOP/COEP) to safely instantiate SharedArrayBuffer without Spectre exposure, combined with explicit Atomics memory fencing between main-thread rendering pipelines and WebAssembly worker pools. Forbids un-synchronized shared memory mutation and illegal main-thread Atomics.wait calls to prevent browser freezing and torn reads.
globs: src/**/*.{ts,tsx}, vite.config.{ts,js}, next.config.{js,mjs,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/coop-atomics-sharedarraybuffer-fencing"
---

# Cross-Origin Isolation and Atomics Fencing for SharedArrayBuffer Concurrency

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unsynchronized SharedArrayBuffer Access and Main-Thread Blocking Atomics Under Insecure Origin Isolation

## System Constraints
You are a Principal Software Architect enforcing enterprise-grade memory synchronization and side-channel security. You must ensure that SharedArrayBuffer is only deployed under cross-origin isolated contexts, that multi-threaded access across Web Workers and the main UI thread enforces acquire-release semantics via Atomics, and that the main thread never blocks on synchronization primitives.

## Strict Guidelines
- Developers MUST verify `self.crossOriginIsolated === true` before initializing any `SharedArrayBuffer` instances.
- Deployment infrastructure and dev servers MUST serve `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (or `credentialless`) headers.
- Engineers MUST NEVER invoke `Atomics.wait()` on the main window thread; `Atomics.waitAsync()` or non-blocking atomic polling MUST be used instead to prevent UI freeze and DOM rendering stall.
- Workers and main-thread pipelines MUST synchronize memory accesses through dedicated atomic control blocks (`Int32Array`) using `Atomics.store`, `Atomics.load`, and `Atomics.notify` instead of mutating raw payload buffers directly.
- Payload buffer updates MUST follow an acquire-release barrier pattern: write payload data, execute `Atomics.store(control, STATE_IDX, READY)` on the producer thread; execute `Atomics.load(control, STATE_IDX)` before reading payload data on the consumer thread.
- All views mapped over a `SharedArrayBuffer` MUST be aligned to their respective element byte sizes to prevent unaligned memory faults in WebAssembly runtimes.

## Bad vs Good Implementations
### Main-Thread / Worker Synchronization via Atomics Ring Fence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Instantiating `SharedArrayBuffer` without validating `crossOriginIsolated` triggers runtime crashes on non-isolated origins. Calling `Atomics.wait` on the main thread throws a browser TypeError because synchronous blocking on the UI event loop is prohibited by the HTML specification. Accessing data fields directly without atomic fencing causes torn reads and memory corruption.
```typescript
// CRITICAL FAILURE: Unsynchronized raw access, no isolation check, illegal main-thread Atomics.wait
export class UnsafeRendererBridge {
  private buffer: SharedArrayBuffer;
  private view: Float64Array;

  constructor(size: number) {
    // Throws ReferenceError if not crossOriginIsolated; vulnerable to data tearing
    this.buffer = new SharedArrayBuffer(size * Float64Array.BYTES_PER_ELEMENT);
    this.view = new Float64Array(this.buffer);
  }

  public readFrameFromWorker(worker: Worker): Float64Array {
    worker.postMessage({ buffer: this.buffer });
    // CRITICAL BUG: Atomics.wait throws a TypeError on the main window thread
    const control = new Int32Array(this.buffer, 0, 1);
    Atomics.wait(control, 0, 0); 
    
    // Race condition: Reading payload without memory barrier semantics
    return this.view.slice(1);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Validates `crossOriginIsolated` prior to buffer allocation. Places a dedicated `Int32Array` control block ahead of the payload, aligned to safe boundaries. Uses non-blocking `Atomics.waitAsync()` on the main UI thread to prevent event-loop stalls, coupled with explicit `Atomics.load` and `Atomics.store` barriers to guarantee sequential consistency and prevent torn reads between WebAssembly workers and the render loop.
```typescript
// PRODUCTION STANDARD: Cross-origin verification, acquire-release atomic fence, non-blocking waitAsync
export const enum BufferState {
  IDLE = 0,
  WRITING = 1,
  READY = 2,
}

export class IsolatedRendererBridge {
  private readonly buffer: SharedArrayBuffer;
  private readonly controlView: Int32Array;
  private readonly dataView: Float64Array;

  constructor(elementCount: number) {
    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {
      throw new Error('ExecutionContext lacks cross-origin isolation (COOP/COEP required for SharedArrayBuffer).');
    }

    const controlBytes = Int32Array.BYTES_PER_ELEMENT * 4; // 16-byte aligned control block
    const dataBytes = elementCount * Float64Array.BYTES_PER_ELEMENT;
    this.buffer = new SharedArrayBuffer(controlBytes + dataBytes);

    this.controlView = new Int32Array(this.buffer, 0, 4);
    this.dataView = new Float64Array(this.buffer, controlBytes, elementCount);
  }

  public async readNextFrameAsync(): Promise<Float64Array> {
    const STATE_INDEX = 0;
    const currentState = Atomics.load(this.controlView, STATE_INDEX);

    if (currentState !== BufferState.READY) {
      // Non-blocking fence: wait asynchronously on the UI thread
      const waitResult = Atomics.waitAsync(this.controlView, STATE_INDEX, currentState);
      if (waitResult.async) {
        await waitResult.value;
      }
    }

    // Acquire fence: Ensure worker memory writes have retired before local load
    Atomics.load(this.controlView, STATE_INDEX);
    
    const frameCopy = new Float64Array(this.dataView.length);
    frameCopy.set(this.dataView);

    // Release fence: Mark buffer back to IDLE and notify waiting worker pool
    Atomics.store(this.controlView, STATE_INDEX, BufferState.IDLE);
    Atomics.notify(this.controlView, STATE_INDEX, 1);

    return frameCopy;
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Cross-Origin Isolation and Atomics Fencing for SharedArrayBuffer Concurrency

Cross-Origin Isolation and Atomics Fencing for SharedArrayBuffer Concurrency defines an industrial-grade behavioral standard for frontend engineering. Mandates strict cross-origin isolation headers (COOP/COEP) to safely instantiate SharedArrayBuffer without Spectre exposure, combined with explicit Atomics memory fencing between main-thread rendering pipelines and WebAssembly worker pools. Forbids un-synchronized shared memory mutation and illegal main-thread Atomics.wait calls to prevent browser freezing and torn reads. 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 SharedArrayBuffer Access and Main-Thread Blocking Atomics Under Insecure Origin Isolation 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 SharedArrayBuffer Access and Main-Thread Blocking Atomics Under Insecure Origin IsolationCritical
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

Developers MUST verify `self.crossOriginIsolated === true` before initializing any `SharedArrayBuffer` instances.

Developers MUST verify `self.crossOriginIsolated === true` before initializing any `SharedArrayBuffer` instances.

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

Deployment infrastructure and dev servers MUST serve `Cross-Origin-Opener-Policy

Deployment infrastructure and dev servers MUST serve `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (or `credentialless`) headers.

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 NEVER invoke `Atomics.wait()` on the main window thread

Engineers MUST NEVER invoke `Atomics.wait()` on the main window thread; `Atomics.waitAsync()` or non-blocking atomic polling MUST be used instead to prevent UI freeze and DOM rendering stall.

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

Workers and main-thread pipelines MUST synchronize memory accesses through dedicated atomic control blocks (`Int32Array`) using `Atomics.store`, `Atomics.load`, and `Atomics.notify` instead of mutating raw payload buffers directly.

Workers and main-thread pipelines MUST synchronize memory accesses through dedicated atomic control blocks (`Int32Array`) using `Atomics.store`, `Atomics.load`, and `Atomics.notify` instead of mutating raw payload buffers directly.

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

Payload buffer updates MUST follow an acquire-release barrier pattern

Payload buffer updates MUST follow an acquire-release barrier pattern: write payload data, execute `Atomics.store(control, STATE_IDX, READY)` on the producer thread; execute `Atomics.load(control, STATE_IDX)` before reading payload data on the consumer thread.

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

All views mapped over a `SharedArrayBuffer` MUST be aligned to their respective element byte sizes to prevent unaligned memory faults in WebAssembly runtimes.

All views mapped over a `SharedArrayBuffer` MUST be aligned to their respective element byte sizes to prevent unaligned memory faults in WebAssembly runtimes.

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 Cross-Origin Isolation and Atomics Fencing for SharedArrayBuffer Concurrency critical for AI coding assistants?

Mandates strict cross-origin isolation headers (COOP/COEP) to safely instantiate SharedArrayBuffer without Spectre exposure, combined with explicit Atomics memory fencing between main-thread rendering pipelines and WebAssembly worker pools. Forbids un-synchronized shared memory mutation and illegal main-thread Atomics.wait calls to prevent browser freezing and torn reads. 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 SharedArrayBuffer Access and Main-Thread Blocking Atomics Under Insecure Origin Isolation) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Cross-Origin