This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: react-native-bridgeless-turbomodule-concurrency-guardrail

React Native Bridgeless TurboModule Concurrency Isolation & JSI Buffer Safety

Enforces strict thread-affinity and memory safety guarantees for React Native Bridgeless C++ TurboModules interacting via the JavaScript Interface (JSI). Prevents direct cross-thread capture or dereferencing of raw jsi::Runtime pointers and guarantees non-torn zero-copy operations over shared ArrayBuffer memory across background worker queues and the JS engine thread.

Prohibited Anti-Pattern: Dereferencing raw JSI pointers or mutating zero-copy memory buffers across asynchronous C++ background threads without CallInvoker synchronization.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native Bridgeless TurboModule Concurrency Isolation & JSI Buffer Safety - Enforces strict thread-affinity and memory safety guarantees for React Native Bridgeless C++ TurboModules interacting via the JavaScript Interface (JSI). Prevents direct cross-thread capture or dereferencing of raw jsi::Runtime pointers and guarantees non-torn zero-copy operations over shared ArrayBuffer memory across background worker queues and the JS engine thread.
globs: src/**/*.{ts,tsx}, native/**/*.{cpp,h,mm}, ios/**/*.{mm,cpp,h}, android/src/main/jni/**/*.{cpp,h}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-turbomodule-concurrency-guardrail"
---

# React Native Bridgeless TurboModule Concurrency Isolation & JSI Buffer Safety

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dereferencing raw JSI pointers or mutating zero-copy memory buffers across asynchronous C++ background threads without CallInvoker synchronization.

## System Constraints
You are a Principal Mobile Architect specializing in React Native's New Architecture, C++ TurboModules, and raw JSI native-interop concurrency invariants. Mandate thread affinity, lifetime bounds, zero-copy safety, and strict asynchronous dispatch via CallInvoker.

## Strict Guidelines
- Engineers MUST NEVER capture or dereference raw `facebook::jsi::Runtime&` or raw `facebook::jsi::Pointer` derivatives (such as `jsi::Object`, `jsi::Value`, `jsi::String`, `jsi::Function`) on any thread other than the specific JS runtime thread they were created on.
- Engineers MUST ALWAYS marshal results back to the JavaScript execution thread using `facebook::react::CallInvoker::invokeAsync` before invoking JS callbacks or resolving Promise wrappers.
- Code MUST isolate zero-copy native memory buffers: any `jsi::ArrayBuffer` accessed across threads must either employ immutable snapshots, native synchronization primitives (e.g., `std::mutex`), or memory-mapped backing stores that prevent data races and torn reads.
- Services MUST explicitly pass a `std::shared_ptr<facebook::react::CallInvoker>` dependency into C++ TurboModule classes to manage lifecycle-safe callback scheduling.
- Components and Native Modules NEVER retain dangling pointers to `jsi::ArrayBuffer` data pointers after JSI method return without guaranteeing that the underlying memory buffer allocation lifetime outlives both threads via RAII structures.

## Bad vs Good Implementations
### Unsafe cross-thread JSI access vs Safe CallInvoker dispatch with thread-safe buffer ownership

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly dereferencing `jsi::Runtime` or calling `jsi::Function::call` on an uncoordinated background `std::thread` violates JSI single-threaded JS runtime invariants. Mutating the raw data pointer in-place without memory barriers causes concurrent access data races against the JS thread.
```cpp
// Anti-Pattern: Capturing raw jsi::Runtime& and jsi::Function across thread boundaries
#include <jsi/jsi.h>
#include <thread>

using namespace facebook;

void processBufferAsync(jsi::Runtime& runtime, const jsi::Object& bufferObj, jsi::Function callback) {
    auto arrayBuffer = bufferObj.getArrayBuffer(runtime);
    uint8_t* rawData = arrayBuffer.data(runtime);
    size_t size = arrayBuffer.size(runtime);

    // CRITICAL BUG: Detached thread captures raw runtime reference & jsi::Function
    // Invoking JSI APIs off the JS thread causes immediate SIGSEGV / torn heap state.
    std::thread([&runtime, rawData, size, callback = std::move(callback)]() mutable {
        for (size_t i = 0; i < size; ++i) {
            rawData[i] ^= 0xFF; // Concurrent mutation without memory barriers
        }
        callback.call(runtime, jsi::Value(true)); // DEREFERENCING RUNTIME ON WORKER THREAD
    }).detach();
}
```

#### Production Standard (Correct)
> **Standard**: Native data is safely extracted while on the JS thread. Long-running work occurs off-thread using pure C++ containers. Execution returns to the JavaScript thread strictly through `CallInvoker::invokeAsync`, where a fresh `jsi::ArrayBuffer` is populated and the callback is invoked on the verified `jsi::Runtime` thread.
```cpp
// Production Standard: Copy-safe background processing and CallInvoker thread marshaling
#include <ReactCommon/CallInvoker.h>
#include <jsi/jsi.h>
#include <memory>
#include <vector>
#include <thread>

using namespace facebook;

void processBufferAsyncSafe(
    jsi::Runtime& runtime,
    const jsi::Object& bufferObj,
    jsi::Function callback,
    std::shared_ptr<react::CallInvoker> jsInvoker) {
    
    auto arrayBuffer = bufferObj.getArrayBuffer(runtime);
    size_t size = arrayBuffer.size(runtime);
    
    // 1. Thread-safe copy into isolated native memory before dispatch
    std::vector<uint8_t> nativeBuffer(size);
    std::memcpy(nativeBuffer.data(), arrayBuffer.data(runtime), size);

    // 2. Wrap JS callback in thread-safe CallInvoker-compatible shared state
    auto callbackValue = std::make_shared<jsi::Value>(runtime, callback);

    // 3. Dispatch computation to background queue without raw JSI dependencies
    std::thread([nativeBuffer = std::move(nativeBuffer), callbackValue, jsInvoker]() mutable {
        for (size_t i = 0; i < nativeBuffer.size(); ++i) {
            nativeBuffer[i] ^= 0xFF;
        }

        // 4. Safely marshal result back to JS thread via CallInvoker
        jsInvoker->invokeAsync([nativeBuffer = std::move(nativeBuffer), callbackValue](jsi::Runtime& rt) {
            auto resultBuffer = rt.global()
                .getPropertyAsFunction(rt, "ArrayBuffer")
                .callAsConstructor(rt, static_cast<double>(nativeBuffer.size()))
                .getObject(rt)
                .getArrayBuffer(rt);
            
            std::memcpy(resultBuffer.data(rt), nativeBuffer.data(), nativeBuffer.size());
            callbackValue->asObject(rt).asFunction(rt).call(rt, std::move(resultBuffer));
        });
    }).detach();
}
```

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: React Native Bridgeless TurboModule Concurrency Isolation & JSI Buffer Safety

React Native Bridgeless TurboModule Concurrency Isolation & JSI Buffer Safety defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread-affinity and memory safety guarantees for React Native Bridgeless C++ TurboModules interacting via the JavaScript Interface (JSI). Prevents direct cross-thread capture or dereferencing of raw jsi::Runtime pointers and guarantees non-torn zero-copy operations over shared ArrayBuffer memory across background worker queues and the JS engine thread. 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: Dereferencing raw JSI pointers or mutating zero-copy memory buffers across asynchronous C++ background threads without CallInvoker synchronization. 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 DriftDereferencing raw JSI pointers or mutating zero-copy memory buffers across asynchronous C++ background threads without CallInvoker synchronization.Critical
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 NEVER capture or dereference raw `facebook

Engineers MUST NEVER capture or dereference raw `facebook::jsi::Runtime&` or raw `facebook::jsi::Pointer` derivatives (such as `jsi::Object`, `jsi::Value`, `jsi::String`, `jsi::Function`) on any thread other than the specific JS runtime thread they were created on.

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 ALWAYS marshal results back to the JavaScript execution thread using `facebook

Engineers MUST ALWAYS marshal results back to the JavaScript execution thread using `facebook::react::CallInvoker::invokeAsync` before invoking JS callbacks or resolving Promise wrappers.

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 MUST isolate zero-copy native memory buffers

Code MUST isolate zero-copy native memory buffers: any `jsi::ArrayBuffer` accessed across threads must either employ immutable snapshots, native synchronization primitives (e.g., `std::mutex`), or memory-mapped backing stores that prevent data races and torn reads.

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 explicitly pass a `std

Services MUST explicitly pass a `std::shared_ptr<facebook::react::CallInvoker>` dependency into C++ TurboModule classes to manage lifecycle-safe callback scheduling.

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 and Native Modules NEVER retain dangling pointers to `jsi

Components and Native Modules NEVER retain dangling pointers to `jsi::ArrayBuffer` data pointers after JSI method return without guaranteeing that the underlying memory buffer allocation lifetime outlives both threads via RAII structures.

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 React Native Bridgeless TurboModule Concurrency Isolation & JSI Buffer Safety critical for AI coding assistants?

Enforces strict thread-affinity and memory safety guarantees for React Native Bridgeless C++ TurboModules interacting via the JavaScript Interface (JSI). Prevents direct cross-thread capture or dereferencing of raw jsi::Runtime pointers and guarantees non-torn zero-copy operations over shared ArrayBuffer memory across background worker queues and the JS engine thread. 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 (Dereferencing raw JSI pointers or mutating zero-copy memory buffers across asynchronous C++ background threads without CallInvoker synchronization.) 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

React