This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri2-mobile-ipc-arraybuffer-lifetime-pinning

Tauri 2.0 Mobile IPC ArrayBuffer Lifetime Pinning & Zero-Copy Stability

Enforces strict memory pinning and explicit ownership handshakes across the Tauri 2.0 Rust-to-WebKit mobile IPC bridge during high-throughput camera and biometric sensor streaming. Prevents use-after-free, double-free, and silent buffer truncation caused by premature JavaScript garbage collection or Rust slice deallocation during asynchronous channel transmission. Mandates explicit transfer-list semantics, channel detachment protocols, and backpressure-regulated frame acknowledgments.

Prohibited Anti-Pattern: Unpinned Ephemeral ArrayBuffer Transmutation Across Mobile WebKit Bridge Leading to SIGSEGV and Silent Memory Corruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Mobile IPC ArrayBuffer Lifetime Pinning & Zero-Copy Stability - Enforces strict memory pinning and explicit ownership handshakes across the Tauri 2.0 Rust-to-WebKit mobile IPC bridge during high-throughput camera and biometric sensor streaming. Prevents use-after-free, double-free, and silent buffer truncation caused by premature JavaScript garbage collection or Rust slice deallocation during asynchronous channel transmission. Mandates explicit transfer-list semantics, channel detachment protocols, and backpressure-regulated frame acknowledgments.
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-mobile-ipc-arraybuffer-lifetime-pinning"
---

# Tauri 2.0 Mobile IPC ArrayBuffer Lifetime Pinning & Zero-Copy Stability

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unpinned Ephemeral ArrayBuffer Transmutation Across Mobile WebKit Bridge Leading to SIGSEGV and Silent Memory Corruption

## System Constraints
You are a Principal Mobile Systems Architect and Rust/WebKit Specialist enforcing rigorous IPC memory safety in Tauri 2.0. Mobile platforms (iOS WKWebView and Android WebView) introduce asynchronous garbage collection sweeps and distinct IPC serialization boundaries that differ sharply from desktop shared memory. When streaming high-throughput sensor data (60fps camera buffers, depth maps, biometric frames), any unpinned ArrayBuffer passed across IPC without explicit lifetime tracking causes catastrophic memory faults (EXC_BAD_ACCESS on iOS, SIGSEGV on Android). Mandate explicit buffer ownership, backpressure flow control, and memory safety invariants across the entire Rust-TypeScript bridge.

## Strict Guidelines
- Engineers MUST ALWAYS use `tauri::ipc::Channel` with raw binary payloads (`tauri::ipc::Response::new(vec)`) rather than base64 strings or JSON-serialized byte arrays for sensor streams exceeding 100 KB/sec.
- Engineers MUST NOT mutate, release, or re-borrow underlying Rust byte buffers until an explicit acknowledgment (`ack`) frame is received over a bidirectional response channel from the frontend WebKit context.
- Frontend consumers MUST detach incoming `ArrayBuffer` instances into dedicated Web Workers or WebCodecs processing contexts using Transferable objects, preventing main-thread WKWebView GC pressure and race conditions.
- Services MUST implement bounded leaky-bucket or drop-oldest backpressure in Rust to guarantee that mobile WebKit's native message queue does not exceed allocation thresholds and trigger memory kills (jetsam on iOS).
- Components NEVER hold long-lived references to `Uint8Array` views created over IPC buffers; views MUST be immediately copied or consumed within a microtask before yielding to the WebKit event loop.

## Bad vs Good Implementations
### Streamed Sensor Buffer Ingestion and Pinning Protocol

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Deserializing camera or biometric buffers via standard JSON event serialization converts binary data into numeric arrays, spiking memory by 8-10x. Failing to signal backpressure to Rust causes native bridge queues to overflow, causing the mobile OS to terminate the host process via OOM (iOS Jetsam / Android LowMemoryKiller).
```typescript
import { listen } from '@tauri-apps/api/event';

// ANTI-PATTERN: Relying on generic JSON/base64 event payloads
// Vulnerable to uncontrolled GC sweeps and silent memory truncation during 60fps streams
export function subscribeToSensorStream(callback: (buffer: Uint8Array) => void) {
  return listen<{ data: number[] }>('camera-frame', (event) => {
    // Allocates massive intermediary JS arrays; GC triggers dropped frames and WebKit crashes
    const rawBytes = new Uint8Array(event.payload.data);
    callback(rawBytes);
    // No backpressure or ACK sent to Rust; IPC buffer queue overflows
  });
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes Tauri 2.0 Channels with native binary transfer semantics. Decouples frame metadata from the raw ArrayBuffer, executes zero-copy dispatch, and issues an explicit RPC acknowledgment to Rust. This ensures the Rust-side buffer memory is pinned and retained in a ring buffer until WebKit confirms ingestion, guaranteeing absolute memory safety and bounded heap usage.
```typescript
import { Channel, invoke } from '@tauri-apps/api/core';

interface StreamFrameMeta {
  frameId: number;
  timestamp: number;
}

type FramePayload = StreamFrameMeta | ArrayBuffer;

export async function subscribeToSensorStream(
  onFrame: (meta: StreamFrameMeta, buffer: ArrayBuffer) => void
): Promise<() => Promise<void>> {
  const channel = new Channel<FramePayload>();
  let pendingMeta: StreamFrameMeta | null = null;

  channel.onmessage = (message: FramePayload) => {
    if (message instanceof ArrayBuffer) {
      if (!pendingMeta) {
        console.error('Orphaned binary buffer received without header metadata');
        return;
      }
      const currentMeta = pendingMeta;
      pendingMeta = null;

      // Dispatch detached zero-copy buffer to consumer
      onFrame(currentMeta, message);

      // Send deterministic ACK back to Rust native stream to release buffer ring slot
      void invoke('acknowledge_sensor_frame', { frameId: currentMeta.frameId });
    } else {
      // Synchronous header arrival strictly preceding the binary payload
      pendingMeta = message;
    }
  };

  await invoke('start_sensor_stream', { onEvent: channel });
  return async () => {
    await invoke('stop_sensor_stream');
  };
}
```

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 Mobile IPC ArrayBuffer Lifetime Pinning & Zero-Copy Stability

Tauri 2.0 Mobile IPC ArrayBuffer Lifetime Pinning & Zero-Copy Stability defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory pinning and explicit ownership handshakes across the Tauri 2.0 Rust-to-WebKit mobile IPC bridge during high-throughput camera and biometric sensor streaming. Prevents use-after-free, double-free, and silent buffer truncation caused by premature JavaScript garbage collection or Rust slice deallocation during asynchronous channel transmission. Mandates explicit transfer-list semantics, channel detachment protocols, and backpressure-regulated frame acknowledgments. 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: Unpinned Ephemeral ArrayBuffer Transmutation Across Mobile WebKit Bridge Leading to SIGSEGV and Silent Memory 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 DriftUnpinned Ephemeral ArrayBuffer Transmutation Across Mobile WebKit Bridge Leading to SIGSEGV and Silent Memory 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 use `tauri

Engineers MUST ALWAYS use `tauri::ipc::Channel` with raw binary payloads (`tauri::ipc::Response::new(vec)`) rather than base64 strings or JSON-serialized byte arrays for sensor streams exceeding 100 KB/sec.

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 mutate, release, or re-borrow underlying Rust byte buffers until an explicit acknowledgment (`ack`) frame is received over a bidirectional response channel from the frontend WebKit context.

Engineers MUST NOT mutate, release, or re-borrow underlying Rust byte buffers until an explicit acknowledgment (`ack`) frame is received over a bidirectional response channel from the frontend WebKit 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

Frontend consumers MUST detach incoming `ArrayBuffer` instances into dedicated Web Workers or WebCodecs processing contexts using Transferable objects, preventing main-thread WKWebView GC pressure and race conditions.

Frontend consumers MUST detach incoming `ArrayBuffer` instances into dedicated Web Workers or WebCodecs processing contexts using Transferable objects, preventing main-thread WKWebView GC pressure and race conditions.

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 implement bounded leaky-bucket or drop-oldest backpressure in Rust to guarantee that mobile WebKit's native message queue does not exceed allocation thresholds and trigger memory kills (jetsam on iOS).

Services MUST implement bounded leaky-bucket or drop-oldest backpressure in Rust to guarantee that mobile WebKit's native message queue does not exceed allocation thresholds and trigger memory kills (jetsam on iOS).

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 hold long-lived references to `Uint8Array` views created over IPC buffers

Components NEVER hold long-lived references to `Uint8Array` views created over IPC buffers; views MUST be immediately copied or consumed within a microtask before yielding to the WebKit event loop.

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 Mobile IPC ArrayBuffer Lifetime Pinning & Zero-Copy Stability critical for AI coding assistants?

Enforces strict memory pinning and explicit ownership handshakes across the Tauri 2.0 Rust-to-WebKit mobile IPC bridge during high-throughput camera and biometric sensor streaming. Prevents use-after-free, double-free, and silent buffer truncation caused by premature JavaScript garbage collection or Rust slice deallocation during asynchronous channel transmission. Mandates explicit transfer-list semantics, channel detachment protocols, and backpressure-regulated frame acknowledgments. 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 (Unpinned Ephemeral ArrayBuffer Transmutation Across Mobile WebKit Bridge Leading to SIGSEGV and Silent Memory 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 MOBILE Rules

View all rules →
1 Rule in Stack

Tauri