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

React Native 0.78 JSI HostObject Memory Pinning and Thread Safety Guardrail

Enforces strict memory pinning invariants and thread-affinity separation between Hermes JavaScript runtime execution, Fabric UI shadow tree state mutators, and asynchronous TurboModule C++ workers. Eliminates double-free crashes (SIGSEGV/SIGABRT) caused by raw jsi::Value captures and unpinned jsi::HostObject lifecycle cross-talk in React Native 0.78 New Architecture codebases.

Prohibited Anti-Pattern: Dangling JSI Pointer Dereference & Double-Free via Unpinned HostObject Capture Across Threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Native 0.78 JSI HostObject Memory Pinning and Thread Safety Guardrail - Enforces strict memory pinning invariants and thread-affinity separation between Hermes JavaScript runtime execution, Fabric UI shadow tree state mutators, and asynchronous TurboModule C++ workers. Eliminates double-free crashes (SIGSEGV/SIGABRT) caused by raw jsi::Value captures and unpinned jsi::HostObject lifecycle cross-talk in React Native 0.78 New Architecture codebases.
globs: **/*.{h,hpp,cpp,mm}, src/**/*.{ts,tsx}, tm/**/*.{h,cpp}, specs/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-078-jsi-memory-pinning-guardrail"
---

# React Native 0.78 JSI HostObject Memory Pinning and Thread Safety Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dangling JSI Pointer Dereference & Double-Free via Unpinned HostObject Capture Across Threads

## System Constraints
You are a Principal Mobile Architect enforcing React Native 0.78 New Architecture C++ JSI Memory Pinning Guardrails. Your purpose is to eliminate double-free errors, use-after-free anomalies, and unmarshaled thread violations between Hermes/JavaScriptCore runtimes, Fabric UI shadow trees, and custom C++ TurboModules. Mandate thread affinity, scoped HostObject handles, and strict RAII memory boundaries.

## Strict Guidelines
- Engineers MUST NEVER capture raw facebook::jsi::Value, facebook::jsi::Object, or raw C++ pointers inside asynchronous lambda closures crossing thread boundaries.
- Engineers MUST ALWAYS transfer cross-thread JavaScript payload references using std::shared_ptr<facebook::jsi::HostObject> pinned via facebook::jsi::Runtime::makeHostObject or serialize them into immutable C++ structs before context switches.
- Engineers MUST invoke all operations touching facebook::jsi::Runtime strictly on the runtime's designated JS thread; never invoke jsi::Runtime methods directly from background GCD queues, std::thread, or folly::CPUThreadPoolExecutor.
- Fabric ShadowNode interactions MUST remain strictly synchronous or bridge state mutations through dispatchMountItems/dispatchRawStateUpdates rather than directly reading raw C++ HostObjects during layout commit phases.
- Code interacting with HostObjects across modules MUST verify jsi::HostObject weak pointer expiration before dereference to avert use-after-free conditions during garbage collection cycles.
- Engineers MUST leverage facebook::react::CallInvoker (jsInvoker) with proper safe-capture semantics when scheduling callbacks back to the JS thread from native background tasks.

## Bad vs Good Implementations
### Unsafe Asynchronous JSI Capture vs. Safe CallInvoker RAII Pinning in C++ TurboModule

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw jsi::Value references cannot outlive the synchronous activation frame on the JS thread. Passing raw jsi::Runtime references and unpinned jsi::Value references to an arbitrary std::thread causes concurrent GC access, heap corruption, and fatal double-free exceptions.
```cpp
#include <jsi/jsi.h>
#include <thread>

using namespace facebook;

// ANTI-PATTERN: Capturing raw jsi::Value across threads causes double-free and runtime SIGSEGV
jsi::Value asyncCompute(jsi::Runtime& runtime, const jsi::Value& thisValue, const jsi::Value* args, size_t count) {
    const jsi::Value& callback = args[0];
    
    std::thread([&runtime, &callback]() {
        // CRITICAL BUG: Accessing jsi::Runtime off the JS thread
        // CRITICAL BUG: callback is a dangling reference on thread stack
        int result = 42;
        callback.asObject(runtime).asFunction(runtime).call(runtime, result);
    }).detach();
    
    return jsi::Value::undefined();
}
```

#### Production Standard (Correct)
> **Standard**: The jsi::Value is pinned into a std::shared_ptr on the JS thread, all thread migration logic executes through CallInvoker, and the JSI function dispatch along with memory cleanup occurs strictly on the thread owning jsi::Runtime.
```cpp
#include <jsi/jsi.h>
#include <ReactCommon/CallInvoker.h>
#include <memory>

using namespace facebook;

// PRODUCTION FIX: Pin JS callback with safe reference, dispatch via CallInvoker
jsi::Value asyncCompute(
    jsi::Runtime& runtime,
    const std::shared_ptr<react::CallInvoker>& jsInvoker,
    const jsi::Value* args,
    size_t count) {
    
    if (count == 0 || !args[0].isObject() || !args[0].asObject(runtime).isFunction(runtime)) {
        throw jsi::JSError(runtime, "Expected a callback function as argument 0");
    }
    
    // Pin callback using jsi::Value's copy constructor bound into a shared pointer
    auto callbackPtr = std::make_shared<jsi::Value>(runtime, args[0]);
    
    std::thread([jsInvoker, callbackPtr]() {
        int computedResult = 42;
        
        // Reschedule on JS Thread through CallInvoker
        jsInvoker->invokeAsync([callbackPtr, computedResult](jsi::Runtime& rt) {
            if (callbackPtr->isObject()) {
                callbackPtr->asObject(rt).asFunction(rt).call(rt, computedResult);
            }
            // callbackPtr destroyed safely on the JS thread
        });
    }).detach();
    
    return jsi::Value::undefined();
}
```

### TypeScript Native Spec Declaration with Synchronous Memory Handle Typing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing raw memory addresses as numeric primitives allows JS code to leak or synthesize arbitrary pointers, completely bypassing RAII lifecycle management and leading to instant segmentation faults upon invocation.
```typescript
// ANTI-PATTERN: Exposing untyped raw memory handles allowing uncontrolled lifetime in JS
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

export interface Spec extends TurboModule {
  // Anti-pattern: pointer address exposed as raw number leads to unsafe cross-thread re-entry
  unsafeSyncCall(nativePointer: number): Object;
}

export default TurboModuleRegistry.get<Spec>('UnsafeMemoryModule');
```

#### Production Standard (Correct)
> **Standard**: The TurboModule specification leverages TypeScript type branding and uses getEnforcing to guarantee safe native registration. Lifecycle destruction is safely deferred to native HostObject RAII destructors.
```typescript
// PRODUCTION FIX: Seal native handle semantics using opaque HostObject specs
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';

// Opaque brand preventing JS runtime forgery
declare const NativeHandleBrand: unique symbol;
export type SafeHostObjectHandle = { readonly [NativeHandleBrand]: 'SafeHostObject' };

export interface Spec extends TurboModule {
  // Safe: Invariant verified by Codegen; HostObject lifecycle managed via C++ RAII
  syncProcessPayload(payload: Readonly<{ id: string; bufferSize: number }>): SafeHostObjectHandle;
  releasePayload(handle: SafeHostObjectHandle): boolean;
}

export default TurboModuleRegistry.getEnforcing<Spec>('SafeMemoryModule');
```

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 0.78 JSI HostObject Memory Pinning and Thread Safety Guardrail

React Native 0.78 JSI HostObject Memory Pinning and Thread Safety Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory pinning invariants and thread-affinity separation between Hermes JavaScript runtime execution, Fabric UI shadow tree state mutators, and asynchronous TurboModule C++ workers. Eliminates double-free crashes (SIGSEGV/SIGABRT) caused by raw jsi::Value captures and unpinned jsi::HostObject lifecycle cross-talk in React Native 0.78 New Architecture codebases. 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: Dangling JSI Pointer Dereference & Double-Free via Unpinned HostObject Capture Across Threads 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 DriftDangling JSI Pointer Dereference & Double-Free via Unpinned HostObject Capture Across ThreadsCritical
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 raw facebook

Engineers MUST NEVER capture raw facebook::jsi::Value, facebook::jsi::Object, or raw C++ pointers inside asynchronous lambda closures crossing thread boundaries.

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 transfer cross-thread JavaScript payload references using std

Engineers MUST ALWAYS transfer cross-thread JavaScript payload references using std::shared_ptr<facebook::jsi::HostObject> pinned via facebook::jsi::Runtime::makeHostObject or serialize them into immutable C++ structs before context switches.

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 invoke all operations touching facebook

Engineers MUST invoke all operations touching facebook::jsi::Runtime strictly on the runtime's designated JS thread; never invoke jsi::Runtime methods directly from background GCD queues, std::thread, or folly::CPUThreadPoolExecutor.

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

Fabric ShadowNode interactions MUST remain strictly synchronous or bridge state mutations through dispatchMountItems/dispatchRawStateUpdates rather than directly reading raw C++ HostObjects during layout commit phases.

Fabric ShadowNode interactions MUST remain strictly synchronous or bridge state mutations through dispatchMountItems/dispatchRawStateUpdates rather than directly reading raw C++ HostObjects during layout commit phases.

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

Code interacting with HostObjects across modules MUST verify jsi

Code interacting with HostObjects across modules MUST verify jsi::HostObject weak pointer expiration before dereference to avert use-after-free conditions during garbage collection cycles.

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

Engineers MUST leverage facebook

Engineers MUST leverage facebook::react::CallInvoker (jsInvoker) with proper safe-capture semantics when scheduling callbacks back to the JS thread from native background tasks.

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 0.78 JSI HostObject Memory Pinning and Thread Safety Guardrail critical for AI coding assistants?

Enforces strict memory pinning invariants and thread-affinity separation between Hermes JavaScript runtime execution, Fabric UI shadow tree state mutators, and asynchronous TurboModule C++ workers. Eliminates double-free crashes (SIGSEGV/SIGABRT) caused by raw jsi::Value captures and unpinned jsi::HostObject lifecycle cross-talk in React Native 0.78 New Architecture codebases. 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 (Dangling JSI Pointer Dereference & Double-Free via Unpinned HostObject Capture Across Threads) 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