This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: rn-new-architecture-jsi-thread-sync-guardrail

TurboModule JSI Lock-Free Thread Synchronization Guardrail

Enforces strict lock-free boundaries within C++ JSI host function implementations in React Native New Architecture TurboModules. Eliminates synchronous platform thread blocking (such as dispatch_sync or std::mutex contentions against main UI queues) to prevent priority inversion deadlocks between Hermes and the native run loop.

Prohibited Anti-Pattern: Synchronously blocking Hermes runtime host functions on UI/platform queues via JSI bindings.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TurboModule JSI Lock-Free Thread Synchronization Guardrail - Enforces strict lock-free boundaries within C++ JSI host function implementations in React Native New Architecture TurboModules. Eliminates synchronous platform thread blocking (such as dispatch_sync or std::mutex contentions against main UI queues) to prevent priority inversion deadlocks between Hermes and the native run loop.
globs: ios/**/*.{h,m,mm,cpp}, android/**/*.{cpp,h,java,kt}, cpp/**/*.{cpp,h}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rn-new-architecture-jsi-thread-sync-guardrail"
---

# TurboModule JSI Lock-Free Thread Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Synchronously blocking Hermes runtime host functions on UI/platform queues via JSI bindings.

## System Constraints
You are a Principal Mobile Systems Architect specializing in React Native New Architecture, TurboModules, and JSI internals. Your mandate is to enforce strict lock-free execution across JSI host function invocations between the Hermes engine and native runtime threads. You must reject any synchronous thread-blocking bridges (e.g., dispatch_sync to UI thread, std::condition_variable blocking inside JSI host functions) that trigger thread priority inversion deadlocks.

## Strict Guidelines
- Engineers MUST ALWAYS treat JSI host functions (jsi::HostFunctionType) as synchronous executions on the Hermes JavaScript thread.
- Engineers MUST NOT call blocking synchronization primitives (`std::mutex::lock`, `std::condition_variable::wait`, `dispatch_sync(dispatch_get_main_queue())`, `CountDownLatch.await()`) inside JSI host function execution frames.
- Engineers MUST NEVER access raw `jsi::Runtime&` or `jsi::Value` instances across thread boundaries without dispatching through `facebook::react::CallInvoker`.
- Code SHOULD utilize lock-free atomic snapshots (`std::atomic<T>`, RCU structures, or folly::AtomicHashMap) for fast-path synchronous state reads required on the JS thread.
- Native operations requiring main-thread state MUST return a `jsi::Value` Promise, execute native work asynchronously via `dispatch_async` or `folly::coro`, and resolve back onto the Hermes runtime using `jsInvoker_->invokeAsync`.
- Services MUST ensure that C++ TurboModule destructors safely drain pending `jsInvoker` callbacks to prevent use-after-free conditions on runtime teardown.

## Bad vs Good Implementations
### JSI Host Function: Blocking UI Dispatch (Deadlock Anti-Pattern) vs Asynchronous CallInvoker Flow

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing `dispatch_sync` targeting the main UI thread inside a synchronous JSI host call will cause an unrecoverable priority inversion deadlock if the main thread is simultaneously waiting for a concurrent Hermes transaction or frame commit.
```cpp
// Anti-Pattern: dispatch_sync to main queue inside JSI host function
// Triggers priority inversion and fatal deadlock when Main UI thread synchronously awaits Hermes
jsi::Value TurboModuleBridge::getLayoutSnapshotSync(
    jsi::Runtime& rt,
    const jsi::Value& thisVal,
    const jsi::Value* args,
    size_t count
) {
    __block std::string layoutJson;
    dispatch_sync(dispatch_get_main_queue(), ^{
        // DEADLOCK RISK: Main thread is blocked waiting for React commit, while JS thread blocks here
        layoutJson = [[PlatformUIManager sharedManager] fetchCurrentLayoutJSON];
    });
    return jsi::String::createFromUtf8(rt, layoutJson);
}
```

#### Production Standard (Correct)
> **Standard**: Uses an asynchronous dispatch to the main queue and marshals the resolution safely back to the Hermes engine via `CallInvoker::invokeAsync`. Neither the Hermes JS thread nor the UI thread is ever subjected to synchronous wait states.
```cpp
// Production Invariant Fix: Return Promise, delegate to background/main, marshal back with CallInvoker
jsi::Value TurboModuleBridge::getLayoutSnapshotAsync(
    jsi::Runtime& rt,
    const jsi::Value& thisVal,
    const jsi::Value* args,
    size_t count
) {
    auto promiseConstructor = rt.global().getPropertyAsFunction(rt, "Promise");
    auto jsInvoker = this->jsInvoker_; // std::shared_ptr<facebook::react::CallInvoker>

    return promiseConstructor.callAsConstructor(
        rt,
        jsi::Function::createFromHostFunction(
            rt,
            jsi::PropNameID::forAscii(rt, "executor"),
            2,
            [jsInvoker](jsi::Runtime& runtime, const jsi::Value&, const jsi::Value* promiseArgs, size_t) -> jsi::Value {
                auto resolve = std::make_shared<jsi::Value>(runtime, promiseArgs[0]);

                dispatch_async(dispatch_get_main_queue(), ^{
                    std::string layoutJson = [[PlatformUIManager sharedManager] fetchCurrentLayoutJSON];
                    jsInvoker->invokeAsync([resolve, layoutJson](jsi::Runtime& rt) {
                        resolve->asObject(rt).asFunction(rt).call(
                            rt,
                            jsi::String::createFromUtf8(rt, layoutJson)
                        );
                    });
                });
                return jsi::Value::undefined();
            }
        )
    );
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: TurboModule JSI Lock-Free Thread Synchronization Guardrail

TurboModule JSI Lock-Free Thread Synchronization Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict lock-free boundaries within C++ JSI host function implementations in React Native New Architecture TurboModules. Eliminates synchronous platform thread blocking (such as dispatch_sync or std::mutex contentions against main UI queues) to prevent priority inversion deadlocks between Hermes and the native run loop. 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: Synchronously blocking Hermes runtime host functions on UI/platform queues via JSI bindings. 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 DriftSynchronously blocking Hermes runtime host functions on UI/platform queues via JSI bindings.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 ALWAYS treat JSI host functions (jsi

Engineers MUST ALWAYS treat JSI host functions (jsi::HostFunctionType) as synchronous executions on the Hermes JavaScript thread.

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 call blocking synchronization primitives (`std

Engineers MUST NOT call blocking synchronization primitives (`std::mutex::lock`, `std::condition_variable::wait`, `dispatch_sync(dispatch_get_main_queue())`, `CountDownLatch.await()`) inside JSI host function execution frames.

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 NEVER access raw `jsi

Engineers MUST NEVER access raw `jsi::Runtime&` or `jsi::Value` instances across thread boundaries without dispatching through `facebook::react::CallInvoker`.

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

Code SHOULD utilize lock-free atomic snapshots (`std

Code SHOULD utilize lock-free atomic snapshots (`std::atomic<T>`, RCU structures, or folly::AtomicHashMap) for fast-path synchronous state reads required on the JS thread.

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

Native operations requiring main-thread state MUST return a `jsi

Native operations requiring main-thread state MUST return a `jsi::Value` Promise, execute native work asynchronously via `dispatch_async` or `folly::coro`, and resolve back onto the Hermes runtime using `jsInvoker_->invokeAsync`.

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 ensure that C++ TurboModule destructors safely drain pending `jsInvoker` callbacks to prevent use-after-free conditions on runtime teardown.

Services MUST ensure that C++ TurboModule destructors safely drain pending `jsInvoker` callbacks to prevent use-after-free conditions on runtime teardown.

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 TurboModule JSI Lock-Free Thread Synchronization Guardrail critical for AI coding assistants?

Enforces strict lock-free boundaries within C++ JSI host function implementations in React Native New Architecture TurboModules. Eliminates synchronous platform thread blocking (such as dispatch_sync or std::mutex contentions against main UI queues) to prevent priority inversion deadlocks between Hermes and the native run loop. 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 (Synchronously blocking Hermes runtime host functions on UI/platform queues via JSI bindings.) 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

TurboModule