This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri2-ipc-reentrancy-ringbuffer-guardrail

Tauri 2.0 IPC Reentrancy Prevention & Bounded Ring-Buffer Bridge Invariant

Enforces non-reentrant, backpressure-managed IPC streaming between Tauri 2.0 native Rust cores and mobile webview runtimes. Prevents webview main-thread starvation and IPC message-loop deadlocks by mandating bounded ring buffers, batched channel-based telemetry, and prohibiting synchronous reentrant invoke calls within event handlers.

Prohibited Anti-Pattern: Unbounded Direct IPC Telemetry Flooding with Synchronous Reentrant Invocations Freezing Mobile Webviews

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 IPC Reentrancy Prevention & Bounded Ring-Buffer Bridge Invariant - Enforces non-reentrant, backpressure-managed IPC streaming between Tauri 2.0 native Rust cores and mobile webview runtimes. Prevents webview main-thread starvation and IPC message-loop deadlocks by mandating bounded ring buffers, batched channel-based telemetry, and prohibiting synchronous reentrant invoke calls within event handlers.
globs: src/**/*.{ts,tsx}, src-tauri/src/**/*.rs
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri2-ipc-reentrancy-ringbuffer-guardrail"
---

# Tauri 2.0 IPC Reentrancy Prevention & Bounded Ring-Buffer Bridge Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Direct IPC Telemetry Flooding with Synchronous Reentrant Invocations Freezing Mobile Webviews

## System Constraints
You are a Principal Mobile Architect enforcing strict Tauri 2.0 IPC safety, non-reentrancy, and ring-buffer throughput limits. Mandate invariants that prevent mobile main-thread locking, WebKit/WebView ANR crashes, and Rust-Webview bridge deadlocks caused by unbounded telemetry streaming or reentrant `invoke` executions.

## Strict Guidelines
- Engineers MUST ALWAYS decouple high-frequency native telemetry using bounded circular ring buffers or Tauri 2.0 Channel primitives (`tauri::ipc::Channel`) with strict backpressure.
- Engineers MUST NOT execute reentrant `invoke()` calls directly inside Tauri `listen()` event listener callbacks; dispatch state mutations asynchronously outside the bridge context.
- Code SHOULD batch high-frequency telemetry events on the webview layer using `requestAnimationFrame` to decouple UI paint cycles from incoming IPC packet rates.
- Services MUST enforce upper bounds on Rust-to-Webview event queues; if the webview bridge is saturated, drop the oldest telemetry frames or signal a backpressure overflow.
- Components NEVER attach un-deduplicated listeners for high-frequency telemetry streams without guaranteed lifecycle teardown and unlisten handle execution.

## Bad vs Good Implementations
### Tauri 2.0 Telemetry Ingestion: Reentrant Invoke vs Bounded Ring-Buffer Channel

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing `invoke` synchronously inside a high-frequency `listen` callback creates an IPC reentrancy deadlock where the native bridge waits on the webview, which in turn waits on an invoke response. Furthermore, processing 120Hz+ events directly into UI callbacks starves the webview event loop, causing severe frame drops and mobile ANR (Application Not Responding) timeouts.
```typescript
import { listen } from '@tauri-apps/api/event';
import { invoke } from '@tauri-apps/api/core';

interface SensorFrame {
  id: string;
  readings: number[];
}

// ANTI-PATTERN: Direct unthrottled event listener executing synchronous reentrant invoke
export function attachSensorBridge(onData: (frame: SensorFrame) => void) {
  const unlistenPromise = listen<SensorFrame>('sensor://telemetry', async (event) => {
    // DEADLOCK HAZARD: Synchronous reentrant invoke back to Rust while Rust IPC queue is locked
    await invoke('telemetry_ack', { frameId: event.payload.id });
    
    // PERF HAZARD: Unthrottled UI update (e.g. 120Hz) saturates WebKit/Android WebView JS thread
    onData(event.payload);
  });

  return () => {
    unlistenPromise.then((unlisten) => unlisten());
  };
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Tauri 2.0's native `Channel` mechanism for unidirectional, non-reentrant IPC transmission. Introduces a bounded ring-buffer (capacity 64) with deterministic tail-dropping on backpressure saturation, and coalesces UI updates via `requestAnimationFrame` to keep the mobile webview main thread fully responsive at 60/120 FPS.
```typescript
import { Channel, invoke } from '@tauri-apps/api/core';

interface SensorFrame {
  id: string;
  readings: number[];
}

// PRODUCTION INVARIANT: Bounded Ring-Buffer with RAF-batched consumption and decoupled channel
export function attachSensorBridge(onBatchUpdate: (frames: SensorFrame[]) => void) {
  const RING_BUFFER_CAPACITY = 64;
  const ringBuffer: SensorFrame[] = [];
  let rafHandle: number | null = null;
  let isSubscribed = true;

  const channel = new Channel<SensorFrame>();
  
  channel.onmessage = (frame: SensorFrame) => {
    if (!isSubscribed) return;

    // Ring-buffer boundary guard: drop oldest frame on overflow to maintain memory invariant
    if (ringBuffer.length >= RING_BUFFER_CAPACITY) {
      ringBuffer.shift();
    }
    ringBuffer.push(frame);

    // Schedule batched paint-cycle consumption without blocking IPC ingestion
    if (rafHandle === null) {
      rafHandle = requestAnimationFrame(() => {
        rafHandle = null;
        if (ringBuffer.length > 0) {
          const batch = ringBuffer.splice(0, ringBuffer.length);
          onBatchUpdate(batch);
        }
      });
    }
  };

  // Non-reentrant channel attachment: Rust writes to channel without waiting for frontend ack
  invoke('start_sensor_stream', { onEvent: channel }).catch((err) => {
    console.error('Failed to initialize telemetry stream channel', err);
  });

  return () => {
    isSubscribed = false;
    if (rafHandle !== null) {
      cancelAnimationFrame(rafHandle);
    }
    invoke('stop_sensor_stream').catch(console.error);
  };
}
```

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: Tauri 2.0 IPC Reentrancy Prevention & Bounded Ring-Buffer Bridge Invariant

Tauri 2.0 IPC Reentrancy Prevention & Bounded Ring-Buffer Bridge Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces non-reentrant, backpressure-managed IPC streaming between Tauri 2.0 native Rust cores and mobile webview runtimes. Prevents webview main-thread starvation and IPC message-loop deadlocks by mandating bounded ring buffers, batched channel-based telemetry, and prohibiting synchronous reentrant invoke calls within event handlers. 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: Unbounded Direct IPC Telemetry Flooding with Synchronous Reentrant Invocations Freezing Mobile Webviews 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 DriftUnbounded Direct IPC Telemetry Flooding with Synchronous Reentrant Invocations Freezing Mobile WebviewsCritical
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 decouple high-frequency native telemetry using bounded circular ring buffers or Tauri 2.0 Channel primitives (`tauri

Engineers MUST ALWAYS decouple high-frequency native telemetry using bounded circular ring buffers or Tauri 2.0 Channel primitives (`tauri::ipc::Channel`) with strict backpressure.

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 execute reentrant `invoke()` calls directly inside Tauri `listen()` event listener callbacks

Engineers MUST NOT execute reentrant `invoke()` calls directly inside Tauri `listen()` event listener callbacks; dispatch state mutations asynchronously outside the bridge context.

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 batch high-frequency telemetry events on the webview layer using `requestAnimationFrame` to decouple UI paint cycles from incoming IPC packet rates.

Code SHOULD batch high-frequency telemetry events on the webview layer using `requestAnimationFrame` to decouple UI paint cycles from incoming IPC packet rates.

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 enforce upper bounds on Rust-to-Webview event queues

Services MUST enforce upper bounds on Rust-to-Webview event queues; if the webview bridge is saturated, drop the oldest telemetry frames or signal a backpressure overflow.

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 attach un-deduplicated listeners for high-frequency telemetry streams without guaranteed lifecycle teardown and unlisten handle execution.

Components NEVER attach un-deduplicated listeners for high-frequency telemetry streams without guaranteed lifecycle teardown and unlisten handle execution.

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 Tauri 2.0 IPC Reentrancy Prevention & Bounded Ring-Buffer Bridge Invariant critical for AI coding assistants?

Enforces non-reentrant, backpressure-managed IPC streaming between Tauri 2.0 native Rust cores and mobile webview runtimes. Prevents webview main-thread starvation and IPC message-loop deadlocks by mandating bounded ring buffers, batched channel-based telemetry, and prohibiting synchronous reentrant invoke calls within event handlers. 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 (Unbounded Direct IPC Telemetry Flooding with Synchronous Reentrant Invocations Freezing Mobile Webviews) 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 MOBILE Rules

View all rules →
1 Rule in Stack

Tauri