This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-worker-native-memory-fence-finalization-isolation

Bun 1.2 Worker Memory Fence & FinalizationRegistry Isolation Guardrail

Enforces strict isolate boundaries and thread-safe lifecycle management for native C-bindings and Node-API handles across Bun 1.2 multi-threaded Workers. Prevents premature resource collection, cross-worker heap pollution, and use-after-free segfaults caused by uncoordinated FinalizationRegistry callbacks on transferred raw pointers.

Prohibited Anti-Pattern: Cross-Worker Raw Pointer Leakage Subject to Asynchronous Foreign-Isolate Finalization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Worker Memory Fence & FinalizationRegistry Isolation Guardrail - Enforces strict isolate boundaries and thread-safe lifecycle management for native C-bindings and Node-API handles across Bun 1.2 multi-threaded Workers. Prevents premature resource collection, cross-worker heap pollution, and use-after-free segfaults caused by uncoordinated FinalizationRegistry callbacks on transferred raw pointers.
globs: src/**/*.{ts,tsx}, workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-worker-native-memory-fence-finalization-isolation"
---

# Bun 1.2 Worker Memory Fence & FinalizationRegistry Isolation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Cross-Worker Raw Pointer Leakage Subject to Asynchronous Foreign-Isolate Finalization

## System Constraints
You are a Principal Systems Architect enforcing strict memory fences and lifecycle isolation for Bun 1.2 multi-threaded workers executing native C/Node-API interop. Mandate thread-safe reference counting, isolate-pinned FinalizationRegistry instances, and explicit ownership transfer protocols to completely eradicate cross-thread heap corruption, double-frees, and use-after-free segfaults.

## Strict Guidelines
- Engineers MUST ALWAYS isolate native C-binding deallocation (e.g., free/destructor calls within FinalizationRegistry) strictly to the isolate thread that originally allocated the pointer.
- Engineers MUST NOT transfer raw numeric pointers (bun:ffi Pointer addresses or unboxed uintptr_t) across Worker postMessage boundaries without an explicit atomic reference increment in native space.
- Code SHOULD employ transferable ArrayBuffers with detached-source semantics or native handle-cloning APIs rather than sharing unbounded raw memory addresses across worker threads.
- Services MUST implement explicit Acquire-Release synchronization fences using Atomics when coordinating shared worker ring buffers or native memory segments backed by SharedArrayBuffer.
- Components NEVER execute FinalizationRegistry.unregister or invoke native teardown routines inside a worker against handles governed by a foreign worker's JavaScriptCore GC cycle.

## Bad vs Good Implementations
### Unsafe Raw Pointer Dispatch with Cross-Thread Finalization Race vs. Thread-Safe Ownership Fence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native handle wrapper is registered in the main isolate's FinalizationRegistry. Once dispatchJobUnsafe exits, the wrapper becomes unreachable on the main thread and its finalizer can invoke free_handle while the background worker is concurrently executing native code against that memory address, triggering SIGSEGV or memory corruption.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

const lib = dlopen("libnative.so", {
  alloc_handle: { args: [FFIType.u32], returns: FFIType.ptr },
  free_handle: { args: [FFIType.ptr], returns: FFIType.void },
});

// ANTI-PATTERN: Native handle registered in main thread GC, but raw pointer passed to worker.
// Main thread can trigger garbage collection and call free_handle while worker is actively dereferencing the pointer.
export function dispatchJobUnsafe(size: number, worker: Worker): void {
  const rawHandle = lib.symbols.alloc_handle(size);
  const wrapper = { handle: rawHandle };

  const registry = new FinalizationRegistry((ptrVal: number) => {
    lib.symbols.free_handle(ptrVal); // Catastrophic use-after-free when worker executes concurrently
  });
  registry.register(wrapper, rawHandle);

  // Passing raw integer pointer across worker isolate boundary
  worker.postMessage({ handleAddress: rawHandle, length: size });
  // wrapper goes out of scope here; GC can finalize immediately
}
```

#### Production Standard (Correct)
> **Standard**: Atomic reference counting is synchronized in native memory (ref_handle) before posting the message across the isolate boundary. The originating isolate unregisters its local GC finalizer before the transfer completes, eliminating the possibility of a concurrent free while the worker acquires ownership and registers its own isolate-local lease.
```typescript
import { dlopen, FFIType } from "bun:ffi";

const lib = dlopen("libnative.so", {
  alloc_handle: { args: [FFIType.u32], returns: FFIType.ptr },
  ref_handle: { args: [FFIType.ptr], returns: FFIType.void },
  unref_handle: { args: [FFIType.ptr], returns: FFIType.void },
});

// PRODUCTION INVARIANT: Atomic reference counting in native space with isolate-bound scoped finalizers.
export class NativeBufferLease {
  private static registry = new FinalizationRegistry((ptrVal: number) => {
    lib.symbols.unref_handle(ptrVal);
  });

  public readonly address: number;
  private active = true;

  constructor(address: number) {
    this.address = address;
    NativeBufferLease.registry.register(this, this.address, this);
  }

  public transferToWorker(worker: Worker, length: number): void {
    if (!this.active) throw new Error("Cannot transfer already disposed or transferred handle");
    
    // Native memory fence: Increment atomic reference count prior to isolate boundary traversal
    lib.symbols.ref_handle(this.address);
    
    // Unregister local isolate finalizer before transfer to prevent race condition
    NativeBufferLease.registry.unregister(this);
    this.active = false;

    worker.postMessage({
      type: "ACQUIRE_NATIVE_HANDLE",
      handleAddress: this.address,
      length,
    });
  }

  public static allocate(size: number): NativeBufferLease {
    const handle = lib.symbols.alloc_handle(size);
    if (!handle) throw new Error("Native allocation failed");
    return new NativeBufferLease(handle);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Worker Memory Fence & FinalizationRegistry Isolation Guardrail

Bun 1.2 Worker Memory Fence & FinalizationRegistry Isolation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces strict isolate boundaries and thread-safe lifecycle management for native C-bindings and Node-API handles across Bun 1.2 multi-threaded Workers. Prevents premature resource collection, cross-worker heap pollution, and use-after-free segfaults caused by uncoordinated FinalizationRegistry callbacks on transferred raw pointers. 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: Cross-Worker Raw Pointer Leakage Subject to Asynchronous Foreign-Isolate Finalization 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 DriftCross-Worker Raw Pointer Leakage Subject to Asynchronous Foreign-Isolate FinalizationCritical
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 isolate native C-binding deallocation (e.g., free/destructor calls within FinalizationRegistry) strictly to the isolate thread that originally allocated the pointer.

Engineers MUST ALWAYS isolate native C-binding deallocation (e.g., free/destructor calls within FinalizationRegistry) strictly to the isolate thread that originally allocated the pointer.

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 transfer raw numeric pointers (bun

Engineers MUST NOT transfer raw numeric pointers (bun:ffi Pointer addresses or unboxed uintptr_t) across Worker postMessage boundaries without an explicit atomic reference increment in native space.

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 SHOULD employ transferable ArrayBuffers with detached-source semantics or native handle-cloning APIs rather than sharing unbounded raw memory addresses across worker threads.

Code SHOULD employ transferable ArrayBuffers with detached-source semantics or native handle-cloning APIs rather than sharing unbounded raw memory addresses across worker threads.

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 explicit Acquire-Release synchronization fences using Atomics when coordinating shared worker ring buffers or native memory segments backed by SharedArrayBuffer.

Services MUST implement explicit Acquire-Release synchronization fences using Atomics when coordinating shared worker ring buffers or native memory segments backed by SharedArrayBuffer.

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 execute FinalizationRegistry.unregister or invoke native teardown routines inside a worker against handles governed by a foreign worker's JavaScriptCore GC cycle.

Components NEVER execute FinalizationRegistry.unregister or invoke native teardown routines inside a worker against handles governed by a foreign worker's JavaScriptCore GC cycle.

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 Bun 1.2 Worker Memory Fence & FinalizationRegistry Isolation Guardrail critical for AI coding assistants?

Enforces strict isolate boundaries and thread-safe lifecycle management for native C-bindings and Node-API handles across Bun 1.2 multi-threaded Workers. Prevents premature resource collection, cross-worker heap pollution, and use-after-free segfaults caused by uncoordinated FinalizationRegistry callbacks on transferred raw pointers. 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 (Cross-Worker Raw Pointer Leakage Subject to Asynchronous Foreign-Isolate Finalization) 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.

1 Rule in Stack

Bun