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

Hermes JSI Zero-Copy Memory Fence and Thread-Affinity Guardrails

Enforces strict thread-affinity checks and atomic memory fences during zero-copy ArrayBuffer sharing between native C++ pipelines and the Hermes JS runtime. Bridgeless TurboModules must never mutate shared backing stores without explicit synchronization or invoke JSI APIs outside the designated Hermes thread. Violating these invariants triggers silent memory corruption, race conditions during GC sweep phases, or unrecoverable fatal SIGSEGV crashes.

Prohibited Anti-Pattern: Unsynchronized Background Thread Mutation and Cross-Thread JSI Object Sharing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hermes JSI Zero-Copy Memory Fence and Thread-Affinity Guardrails - Enforces strict thread-affinity checks and atomic memory fences during zero-copy ArrayBuffer sharing between native C++ pipelines and the Hermes JS runtime. Bridgeless TurboModules must never mutate shared backing stores without explicit synchronization or invoke JSI APIs outside the designated Hermes thread. Violating these invariants triggers silent memory corruption, race conditions during GC sweep phases, or unrecoverable fatal SIGSEGV crashes.
globs: cpp/**/*.{cpp,h,hpp}, ios/**/*.{mm,cpp,h}, android/src/main/jni/**/*.{cpp,h}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-native-bridgeless-jsi-zerocopy-memory-fence"
---

# Hermes JSI Zero-Copy Memory Fence and Thread-Affinity Guardrails

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Background Thread Mutation and Cross-Thread JSI Object Sharing

## System Constraints
You are a Principal Software Architect enforcing zero-copy memory safety in React Native New Architecture (Bridgeless) JSI modules. JSI runtimes (Hermes) are strictly single-threaded and non-reentrant. You must prevent cross-thread JSI pointer dereferencing, enforce explicit atomic memory fences (acquire/release) on shared mutable buffers, ensure TurboModule buffer ownership lifetimes survive JS garbage collection via pinned HostObjects, and verify all native-to-JS bridge returns dispatch via react::CallInvoker.

## Strict Guidelines
- Engineers MUST ALWAYS verify thread affinity before interacting with any facebook::jsi::Runtime instance, asserting that JSI execution occurs strictly on the Hermes JS thread.
- Engineers MUST NOT access, create, or mutate facebook::jsi::Value, Object, or ArrayBuffer references on non-JS worker threads without dispatching through facebook::react::CallInvoker.
- Code MUST employ atomic memory fences (std::atomic_thread_fence with std::memory_order_release / acquire) or double-buffering when native producer threads populate underlying raw byte buffers read by Hermes.
- Native zero-copy ArrayBuffer implementations MUST implement facebook::jsi::MutableBuffer with deterministic lifetime guarantees to prevent Use-After-Free (UAF) during Hermes garbage collection cycles.
- TypeScript interfaces MUST mark zero-copy ArrayBuffer handles as read-only transfer wrappers and invalidate them after explicit consumption to prevent concurrent JS-side mutation.
- Services MUST NEVER invoke blocking synchronization primitives (e.g., std::mutex lock) on the Hermes runtime thread that wait on asynchronous native producer queues.

## Bad vs Good Implementations
### JSI Zero-Copy Buffer Access with Atomic Memory Fence and CallInvoker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing JSI methods on a background thread violates Hermes thread affinity, corrupting internal runtime pointers and heap state. Lack of atomic memory fences allows CPU cache incoherency on multi-core ARM chips, while exposing raw unpinned memory leads to Use-After-Free if the buffer lifecycle terminates prematurely.
```cpp
// CRITICAL HAZARD: Directly creating JSI ArrayBuffer on a background hardware thread
// and passing a raw heap pointer with no memory barriers or thread validation.
void HardwareStream::onFrameData(uint8_t* rawBuffer, size_t size) {
    std::thread([this, rawBuffer, size]() {
        // FATAL: Accessing jsi::Runtime concurrently from background thread!
        // No memory fence: Hermes may read stale CPU cache lines.
        auto jsBuffer = facebook::jsi::ArrayBuffer(
            *hermesRuntime_,
            std::make_shared<UnsafeRawBuffer>(rawBuffer, size)
        );
        jsCallback_->call(*hermesRuntime_, jsBuffer);
    }).detach();
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern enforces thread boundary discipline using CallInvoker::invokeAsync, encapsulates memory ownership into a ref-counted jsi::MutableBuffer to eliminate UAF risks, and enforces hardware-level cache consistency across cores via release/acquire memory fences.
```cpp
// PRODUCTION SAFE: Thread-safe Pinned Buffer with Release/Acquire Memory Fence
class SafePinnedBuffer : public facebook::jsi::MutableBuffer {
public:
    SafePinnedBuffer(std::vector<uint8_t>&& data) : data_(std::move(data)) {}
    size_t size() const override { return data_.size(); }
    uint8_t* data() override { return data_.data(); }
private:
    std::vector<uint8_t> data_;
};

void HardwareStream::onFrameData(std::vector<uint8_t> frameData) {
    // Native Producer: Move buffer to ensure exclusive ownership
    auto pinnedBuffer = std::make_shared<SafePinnedBuffer>(std::move(frameData));
    
    // Establish memory fence: ensure payload writes are visible prior to dispatch
    std::atomic_thread_fence(std::memory_order_release);

    // Dispatch to Hermes JS Thread via CallInvoker
    jsCallInvoker_->invokeAsync([this, pinnedBuffer]() noexcept {
        // Hermes Consumer: Acquire memory fence before reading
        std::atomic_thread_fence(std::memory_order_acquire);
        
        facebook::jsi::Runtime& rt = getRuntime();
        auto arrayBuffer = rt.global().getPropertyAsFunction(rt, "ArrayBuffer");
        
        auto jsiArrayBuffer = facebook::jsi::ArrayBuffer(
            rt,
            pinnedBuffer
        );
        
        jsCallback_->asObject(rt).asFunction(rt).call(rt, std::move(jsiArrayBuffer));
    });
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hermes JSI Zero-Copy Memory Fence and Thread-Affinity Guardrails

Hermes JSI Zero-Copy Memory Fence and Thread-Affinity Guardrails defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread-affinity checks and atomic memory fences during zero-copy ArrayBuffer sharing between native C++ pipelines and the Hermes JS runtime. Bridgeless TurboModules must never mutate shared backing stores without explicit synchronization or invoke JSI APIs outside the designated Hermes thread. Violating these invariants triggers silent memory corruption, race conditions during GC sweep phases, or unrecoverable fatal SIGSEGV crashes. 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: Unsynchronized Background Thread Mutation and Cross-Thread JSI Object Sharing 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 DriftUnsynchronized Background Thread Mutation and Cross-Thread JSI Object SharingCritical
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 verify thread affinity before interacting with any facebook

Engineers MUST ALWAYS verify thread affinity before interacting with any facebook::jsi::Runtime instance, asserting that JSI execution occurs strictly on the Hermes 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.
2

Engineers MUST NOT access, create, or mutate facebook

Engineers MUST NOT access, create, or mutate facebook::jsi::Value, Object, or ArrayBuffer references on non-JS worker threads 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.
3

Code MUST employ atomic memory fences (std

Code MUST employ atomic memory fences (std::atomic_thread_fence with std::memory_order_release / acquire) or double-buffering when native producer threads populate underlying raw byte buffers read by Hermes.

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

Native zero-copy ArrayBuffer implementations MUST implement facebook

Native zero-copy ArrayBuffer implementations MUST implement facebook::jsi::MutableBuffer with deterministic lifetime guarantees to prevent Use-After-Free (UAF) during Hermes 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.
5

TypeScript interfaces MUST mark zero-copy ArrayBuffer handles as read-only transfer wrappers and invalidate them after explicit consumption to prevent concurrent JS-side mutation.

TypeScript interfaces MUST mark zero-copy ArrayBuffer handles as read-only transfer wrappers and invalidate them after explicit consumption to prevent concurrent JS-side mutation.

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 NEVER invoke blocking synchronization primitives (e.g., std

Services MUST NEVER invoke blocking synchronization primitives (e.g., std::mutex lock) on the Hermes runtime thread that wait on asynchronous native producer queues.

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 Hermes JSI Zero-Copy Memory Fence and Thread-Affinity Guardrails critical for AI coding assistants?

Enforces strict thread-affinity checks and atomic memory fences during zero-copy ArrayBuffer sharing between native C++ pipelines and the Hermes JS runtime. Bridgeless TurboModules must never mutate shared backing stores without explicit synchronization or invoke JSI APIs outside the designated Hermes thread. Violating these invariants triggers silent memory corruption, race conditions during GC sweep phases, or unrecoverable fatal SIGSEGV crashes. 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 (Unsynchronized Background Thread Mutation and Cross-Thread JSI Object Sharing) 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

Hermes