This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: webgpu-compute-workgroup-barrier-memory-coherency

WebGPU Workgroup Barrier Synchronization and Memory Layout Invariant

Mandates explicit workgroup barrier synchronization and strict memory layout alignments (16-byte struct alignment and 256-byte dynamic offset boundaries) in WebGPU compute pipelines. Prevents GPU race conditions, torn reads, and device loss during high-frequency client-side neural network tensor operations. Enforces deterministic coherency between cooperative thread loads into workgroup shared memory and subsequent compute passes.

Prohibited Anti-Pattern: Missing workgroupBarrier() and unpadded WGSL uniform structs causing GPU race conditions and silent output corruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebGPU Workgroup Barrier Synchronization and Memory Layout Invariant - Mandates explicit workgroup barrier synchronization and strict memory layout alignments (16-byte struct alignment and 256-byte dynamic offset boundaries) in WebGPU compute pipelines. Prevents GPU race conditions, torn reads, and device loss during high-frequency client-side neural network tensor operations. Enforces deterministic coherency between cooperative thread loads into workgroup shared memory and subsequent compute passes.
globs: src/**/*.{ts,tsx,wgsl}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webgpu-compute-workgroup-barrier-memory-coherency"
---

# WebGPU Workgroup Barrier Synchronization and Memory Layout Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Missing workgroupBarrier() and unpadded WGSL uniform structs causing GPU race conditions and silent output corruption

## System Constraints
You are a Principal GPU Systems Architect enforcing strict concurrency invariants in WebGPU compute shaders and TypeScript client drivers. You must reject any WGSL compute kernel that reads from shared workgroup memory without preceding workgroupBarrier() synchronizations, and reject any buffer allocation that violates WGSL 16-byte struct alignment or device minUniformBufferOffsetAlignment constraints.

## Strict Guidelines
- Engineers MUST ALWAYS insert `workgroupBarrier()` between cooperative write phases to `var<workgroup>` memory and subsequent read/compute phases across all invocation threads.
- Engineers MUST NOT read or write to `var<workgroup>` across thread boundaries without an intervening `workgroupBarrier()` execution within convergent control flow.
- Code SHOULD align uniform and storage buffer bindings to explicit 16-byte alignment boundaries using `@align(16)` or manual padding to conform with WebGPU memory layout specifications.
- Services MUST validate that dynamic buffer offsets passed to `GPURenderPassEncoder.setBindGroup` or `GPUComputePassEncoder.setBindGroup` are strict multiples of `adapter.limits.minUniformBufferOffsetAlignment` (typically 256 bytes).
- Components NEVER conditionally bypass workgroup barriers within divergent non-uniform branching conditions (`if (local_invocation_id.x > 0) { workgroupBarrier(); }`), which causes undefined hardware lockups and GPU hangs.

## Bad vs Good Implementations
### Workgroup Memory Reduction and Uniform Struct Layout Alignment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The WGSL shader populates `shared_tile` from multiple threads and immediately aggregates the result in thread 0 without calling `workgroupBarrier()`. This causes non-deterministic reads and silent numerical drift. Additionally, the Uniforms struct lacks 16-byte boundary padding, and the dynamic buffer offset (100) violates the WebGPU 256-byte alignment requirement, causing device crash.
```typescript
// Anti-pattern: Missing workgroupBarrier() leads to data races;
// Unpadded uniform structure leads to misaligned memory offsets.
export const BAD_COMPUTE_SHADER = `
struct Uniforms {
  batch_size: u32,   // 4 bytes
  learning_rate: f32 // 4 bytes - total 8 bytes, violates 16-byte alignment!
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<storage, read_write> data: array<f32>;

var<workgroup> shared_tile: array<f32, 64>;

@compute @workgroup_size(64, 1, 1)
fn main(@builtin(local_invocation_index) local_id: u32) {
  shared_tile[local_id] = data[local_id];
  // BUG: No workgroupBarrier()! Adjacent threads read stale/unwritten shared data
  if (local_id == 0u) {
    var acc: f32 = 0.0;
    for (var i: u32 = 0u; i < 64u; i = i + 1u) {
      acc = acc + shared_tile[i];
    }
    data[0] = acc * uniforms.learning_rate;
  }
}
`;

export function badDispatch(device: GPUDevice, pass: GPUComputePassEncoder, pipeline: GPUComputePipeline, bg: GPUBindGroup) {
  pass.setPipeline(pipeline);
  // BUG: Offset is 100 bytes, which violates the 256-byte minUniformBufferOffsetAlignment!
  pass.setBindGroup(0, bg, [100]);
  pass.dispatchWorkgroups(1);
}
```

#### Production Standard (Correct)
> **Standard**: The WGSL compute shader enforces cooperative synchronization via `workgroupBarrier()` following shared memory loads and within each step of the tree-reduction loop. The uniform struct is explicitly padded to 16 bytes. Dynamic buffer offsets are validated against `device.limits.minUniformBufferOffsetAlignment` before pass encoding, preventing hardware device loss.
```typescript
// Production-grade: Explicit workgroup synchronization and aligned memory buffers
export const GOOD_COMPUTE_SHADER = `
struct Uniforms {
  batch_size: u32,
  learning_rate: f32,
  _padding: vec2<f32>, // Pad struct to explicit 16-byte alignment
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<storage, read_write> data: array<f32>;

var<workgroup> shared_tile: array<f32, 64>;

@compute @workgroup_size(64, 1, 1)
fn main(@builtin(local_invocation_index) local_id: u32) {
  // Phase 1: Cooperative load
  shared_tile[local_id] = data[local_id];

  // INVARIANT: Synchronize all workgroup threads before consuming shared memory
  workgroupBarrier();

  // Phase 2: Tree-based reduction inside convergent execution
  for (var stride: u32 = 32u; stride > 0u; stride = stride >> 1u) {
    if (local_id < stride) {
      shared_tile[local_id] = shared_tile[local_id] + shared_tile[local_id + stride];
    }
    workgroupBarrier();
  }

  // Phase 3: Root thread write-back
  if (local_id == 0u) {
    data[0] = shared_tile[0] * uniforms.learning_rate;
  }
}
`;

export function goodDispatch(device: GPUDevice, pass: GPUComputePassEncoder, pipeline: GPUComputePipeline, bg: GPUBindGroup, byteOffset: number) {
  const minAlignment = device.limits.minUniformBufferOffsetAlignment;
  if (byteOffset % minAlignment !== 0) {
    throw new RangeError(`Dynamic buffer offset (${byteOffset}) must align to ${minAlignment} bytes`);
  }
  pass.setPipeline(pipeline);
  pass.setBindGroup(0, bg, [byteOffset]);
  pass.dispatchWorkgroups(1);
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebGPU Workgroup Barrier Synchronization and Memory Layout Invariant

WebGPU Workgroup Barrier Synchronization and Memory Layout Invariant defines an industrial-grade behavioral standard for frontend engineering. Mandates explicit workgroup barrier synchronization and strict memory layout alignments (16-byte struct alignment and 256-byte dynamic offset boundaries) in WebGPU compute pipelines. Prevents GPU race conditions, torn reads, and device loss during high-frequency client-side neural network tensor operations. Enforces deterministic coherency between cooperative thread loads into workgroup shared memory and subsequent compute passes. 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: Missing workgroupBarrier() and unpadded WGSL uniform structs causing GPU race conditions and silent output corruption 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 DriftMissing workgroupBarrier() and unpadded WGSL uniform structs causing GPU race conditions and silent output corruptionCritical
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 insert `workgroupBarrier()` between cooperative write phases to `var<workgroup>` memory and subsequent read/compute phases across all invocation threads.

Engineers MUST ALWAYS insert `workgroupBarrier()` between cooperative write phases to `var<workgroup>` memory and subsequent read/compute phases across all invocation threads.

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 read or write to `var<workgroup>` across thread boundaries without an intervening `workgroupBarrier()` execution within convergent control flow.

Engineers MUST NOT read or write to `var<workgroup>` across thread boundaries without an intervening `workgroupBarrier()` execution within convergent control flow.

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

Code SHOULD align uniform and storage buffer bindings to explicit 16-byte alignment boundaries using `@align(16)` or manual padding to conform with WebGPU memory layout specifications.

Code SHOULD align uniform and storage buffer bindings to explicit 16-byte alignment boundaries using `@align(16)` or manual padding to conform with WebGPU memory layout specifications.

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 validate that dynamic buffer offsets passed to `GPURenderPassEncoder.setBindGroup` or `GPUComputePassEncoder.setBindGroup` are strict multiples of `adapter.limits.minUniformBufferOffsetAlignment` (typically 256 bytes).

Services MUST validate that dynamic buffer offsets passed to `GPURenderPassEncoder.setBindGroup` or `GPUComputePassEncoder.setBindGroup` are strict multiples of `adapter.limits.minUniformBufferOffsetAlignment` (typically 256 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.
5

Components NEVER conditionally bypass workgroup barriers within divergent non-uniform branching conditions (`if (local_invocation_id.x > 0) { workgroupBarrier()

Components NEVER conditionally bypass workgroup barriers within divergent non-uniform branching conditions (`if (local_invocation_id.x > 0) { workgroupBarrier(); }`), which causes undefined hardware lockups and GPU hangs.

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 WebGPU Workgroup Barrier Synchronization and Memory Layout Invariant critical for AI coding assistants?

Mandates explicit workgroup barrier synchronization and strict memory layout alignments (16-byte struct alignment and 256-byte dynamic offset boundaries) in WebGPU compute pipelines. Prevents GPU race conditions, torn reads, and device loss during high-frequency client-side neural network tensor operations. Enforces deterministic coherency between cooperative thread loads into workgroup shared memory and subsequent compute passes. 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 (Missing workgroupBarrier() and unpadded WGSL uniform structs causing GPU race conditions and silent output corruption) 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

WebGPU