This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: webgpu-device-loss-recovery-buffer-reclamation

WebGPU Device Loss Recovery and Idempotent VRAM Buffer Reclamation Standard

Mandates asynchronous WebGPU context restoration and idempotent VRAM buffer staging pipelines to guarantee UI resilience against OS-level compositor drops, GPU driver resets (TDR), and system sleep/wake cycles. Enforces complete resource tracking and explicit buffer destruction to prevent GPU memory leaks and client runtime crashes.

Prohibited Anti-Pattern: Monolithic GPU Resource Initialization Assuming Indestructible GPUDevice Lifetimes Without Loss Recovery Or Explicit Reclamation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebGPU Device Loss Recovery and Idempotent VRAM Buffer Reclamation Standard - Mandates asynchronous WebGPU context restoration and idempotent VRAM buffer staging pipelines to guarantee UI resilience against OS-level compositor drops, GPU driver resets (TDR), and system sleep/wake cycles. Enforces complete resource tracking and explicit buffer destruction to prevent GPU memory leaks and client runtime crashes.
globs: src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/webgpu-device-loss-recovery-buffer-reclamation"
---

# WebGPU Device Loss Recovery and Idempotent VRAM Buffer Reclamation Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Monolithic GPU Resource Initialization Assuming Indestructible GPUDevice Lifetimes Without Loss Recovery Or Explicit Reclamation

## System Constraints
You are a Principal Software Architect enforcing WebGPU reliability invariants. You must mandate that all WebGPU device contexts are treated as ephemeral handles subject to OS-level preemption, driver updates, and compositor drops. You must enforce strict device.lost lifecycle observers, epoch-based state tracking, idempotent VRAM buffer recreation, and explicit resource destruction.

## Strict Guidelines
- Engineers MUST ALWAYS attach a handler to device.lost immediately upon GPUDevice creation to handle 'destroyed' and 'unknown' reasons asynchronously.
- Engineers MUST NOT cache raw GPUBuffer, GPUTexture, or GPURenderPipeline references without an associated epoch or registry key that supports idempotent recreation from host-side source data.
- Engineers MUST ALWAYS explicitly invoke .destroy() on active GPUBuffer and GPUTexture allocations during teardown or re-allocation cycles to prevent unmanaged host-VRAM memory retention.
- Render loops MUST cancel active requestAnimationFrame cycles immediately when device.lost resolves and pause execution until the device epoch advances post-recovery.
- Components NEVER reissue GPUQueue.writeBuffer or GPUQueue.submit operations against a device whose .lost promise has settled.
- Services MUST implement exponential backoff with jitter when re-requesting GPUAdapter and GPUDevice after an OS compositor drop or TDR event.

## Bad vs Good Implementations
### WebGPU Context Loss & Idempotent Buffer Staging Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The class assumes the GPUDevice will remain valid for the lifespan of the application. It ignores device.lost, meaning that a Windows TDR, sleep/wake event, or browser tab backgrounding will leave the render loop submitting commands to a dead device, causing uncaught exceptions, frozen UI, and VRAM leaks due to the lack of .destroy() cleanup.
```typescript
export class BadMeshRenderer {
  private device!: GPUDevice;
  private vertexBuffer!: GPUBuffer;

  async init(canvas: HTMLCanvasElement, meshData: Float32Array): Promise<void> {
    // ANTI-PATTERN: Device is assumed to live forever; device.lost is ignored.
    const adapter = await navigator.gpu.requestAdapter();
    this.device = await adapter!.requestDevice();
    const ctx = canvas.getContext('webgpu')!;
    ctx.configure({ device: this.device, format: 'bgra8unorm' });

    // Allocating buffer without a recreation path or explicit lifecycle cleanup
    this.vertexBuffer = this.device.createBuffer({
      size: meshData.byteLength,
      usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
    });
    this.device.queue.writeBuffer(this.vertexBuffer, 0, meshData.buffer);

    const render = () => {
      // Unhandled crash when OS compositor drops device during TDR or sleep
      const encoder = this.device.createCommandEncoder();
      const pass = encoder.beginRenderPass({ colorAttachments: [] });
      pass.end();
      this.device.queue.submit([encoder.finish()]);
      requestAnimationFrame(render);
    };
    requestAnimationFrame(render);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements an epoch-guarded lifecycle manager with a structured device.lost handler. Staged buffer data is kept in host memory so that upon OS-level context loss (TDR or sleep), the renderer pauses its frame loop, tears down stale VRAM allocations via .destroy(), implements exponential backoff reconnection, reconfigures the swapchain, and restages all vertex/index buffers seamlessly.
```typescript
export interface StagedBufferDescriptor {
  label: string;
  usage: GPUBufferUsageFlags;
  data: ArrayBufferView;
}

export class ResilientMeshRenderer {
  private device: GPUDevice | null = null;
  private context: GPUCanvasContext | null = null;
  private buffers = new Map<string, GPUBuffer>();
  private hostDataRegistry = new Map<string, StagedBufferDescriptor>();
  private isRecovering = false;
  private rafId: number | null = null;
  private epoch = 0;

  async init(canvas: HTMLCanvasElement): Promise<void> {
    this.context = canvas.getContext('webgpu');
    if (!this.context) throw new Error('WebGPU unsupported');
    await this.acquireContext();
  }

  private async acquireContext(): Promise<void> {
    const currentEpoch = ++this.epoch;
    this.cleanupCurrentDevice();

    const adapter = await navigator.gpu.requestAdapter();
    if (!adapter) throw new Error('No compatible GPU adapter found');

    const device = await adapter.requestDevice();
    this.device = device;
    this.context!.configure({
      device: this.device,
      format: navigator.gpu.getPreferredCanvasFormat()
    });

    // Monitor device loss asynchronously
    device.lost.then((info) => {
      console.warn(`[WebGPU] Device lost (Reason: ${info.reason}): ${info.message}`);
      if (this.epoch === currentEpoch) {
        this.handleDeviceLoss();
      }
    });

    this.restageBuffers();
    this.startRenderLoop();
  }

  public registerBuffer(id: string, descriptor: StagedBufferDescriptor): void {
    this.hostDataRegistry.set(id, descriptor);
    if (this.device && !this.isRecovering) {
      this.createAndUploadBuffer(id, descriptor);
    }
  }

  private createAndUploadBuffer(id: string, desc: StagedBufferDescriptor): void {
    if (!this.device) return;
    const existing = this.buffers.get(id);
    if (existing) {
      existing.destroy();
      this.buffers.delete(id);
    }
    const buffer = this.device.createBuffer({
      label: desc.label,
      size: Math.ceil(desc.data.byteLength / 4) * 4,
      usage: desc.usage | GPUBufferUsage.COPY_DST
    });
    this.device.queue.writeBuffer(buffer, 0, desc.data.buffer, desc.data.byteOffset, desc.data.byteLength);
    this.buffers.set(id, buffer);
  }

  private restageBuffers(): void {
    for (const [id, desc] of this.hostDataRegistry.entries()) {
      this.createAndUploadBuffer(id, desc);
    }
  }

  private cleanupCurrentDevice(): void {
    if (this.rafId !== null) {
      cancelAnimationFrame(this.rafId);
      this.rafId = null;
    }
    for (const buffer of this.buffers.values()) {
      buffer.destroy();
    }
    this.buffers.clear();
    if (this.device) {
      this.device.destroy();
      this.device = null;
    }
  }

  private async handleDeviceLoss(): Promise<void> {
    if (this.isRecovering) return;
    this.isRecovering = true;
    this.cleanupCurrentDevice();

    const maxRetries = 5;
    let attempt = 0;
    while (attempt < maxRetries) {
      try {
        await new Promise((res) => setTimeout(res, Math.min(1000 * 2 ** attempt, 8000)));
        await this.acquireContext();
        this.isRecovering = false;
        return;
      } catch (err) {
        attempt++;
        console.error(`[WebGPU] Reconnect attempt ${attempt} failed:`, err);
      }
    }
    this.isRecovering = false;
    throw new Error('WebGPU context recovery exhausted maximum retries.');
  }

  private startRenderLoop(): void {
    const render = () => {
      if (!this.device || this.isRecovering) return;
      const encoder = this.device.createCommandEncoder();
      const pass = encoder.beginRenderPass({
        colorAttachments: [{
          view: this.context!.getCurrentTexture().createView(),
          clearValue: { r: 0.05, g: 0.05, b: 0.05, a: 1.0 },
          loadOp: 'clear',
          saveOp: 'store'
        }]
      });
      pass.end();
      this.device.queue.submit([encoder.finish()]);
      this.rafId = requestAnimationFrame(render);
    };
    this.rafId = requestAnimationFrame(render);
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: WebGPU Device Loss Recovery and Idempotent VRAM Buffer Reclamation Standard

WebGPU Device Loss Recovery and Idempotent VRAM Buffer Reclamation Standard defines an industrial-grade behavioral standard for frontend engineering. Mandates asynchronous WebGPU context restoration and idempotent VRAM buffer staging pipelines to guarantee UI resilience against OS-level compositor drops, GPU driver resets (TDR), and system sleep/wake cycles. Enforces complete resource tracking and explicit buffer destruction to prevent GPU memory leaks and client runtime crashes. 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: Monolithic GPU Resource Initialization Assuming Indestructible GPUDevice Lifetimes Without Loss Recovery Or Explicit Reclamation 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 DriftMonolithic GPU Resource Initialization Assuming Indestructible GPUDevice Lifetimes Without Loss Recovery Or Explicit ReclamationCritical
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 attach a handler to device.lost immediately upon GPUDevice creation to handle 'destroyed' and 'unknown' reasons asynchronously.

Engineers MUST ALWAYS attach a handler to device.lost immediately upon GPUDevice creation to handle 'destroyed' and 'unknown' reasons asynchronously.

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 cache raw GPUBuffer, GPUTexture, or GPURenderPipeline references without an associated epoch or registry key that supports idempotent recreation from host-side source data.

Engineers MUST NOT cache raw GPUBuffer, GPUTexture, or GPURenderPipeline references without an associated epoch or registry key that supports idempotent recreation from host-side source 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.
3

Engineers MUST ALWAYS explicitly invoke .destroy() on active GPUBuffer and GPUTexture allocations during teardown or re-allocation cycles to prevent unmanaged host-VRAM memory retention.

Engineers MUST ALWAYS explicitly invoke .destroy() on active GPUBuffer and GPUTexture allocations during teardown or re-allocation cycles to prevent unmanaged host-VRAM memory retention.

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

Render loops MUST cancel active requestAnimationFrame cycles immediately when device.lost resolves and pause execution until the device epoch advances post-recovery.

Render loops MUST cancel active requestAnimationFrame cycles immediately when device.lost resolves and pause execution until the device epoch advances post-recovery.

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 reissue GPUQueue.writeBuffer or GPUQueue.submit operations against a device whose .lost promise has settled.

Components NEVER reissue GPUQueue.writeBuffer or GPUQueue.submit operations against a device whose .lost promise has settled.

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

Services MUST implement exponential backoff with jitter when re-requesting GPUAdapter and GPUDevice after an OS compositor drop or TDR event.

Services MUST implement exponential backoff with jitter when re-requesting GPUAdapter and GPUDevice after an OS compositor drop or TDR event.

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 Device Loss Recovery and Idempotent VRAM Buffer Reclamation Standard critical for AI coding assistants?

Mandates asynchronous WebGPU context restoration and idempotent VRAM buffer staging pipelines to guarantee UI resilience against OS-level compositor drops, GPU driver resets (TDR), and system sleep/wake cycles. Enforces complete resource tracking and explicit buffer destruction to prevent GPU memory leaks and client runtime crashes. 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 (Monolithic GPU Resource Initialization Assuming Indestructible GPUDevice Lifetimes Without Loss Recovery Or Explicit Reclamation) 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