Skip to content

perf(runtime): settle Promises through the event loop; check threads, not run loops - #608

Merged
edusperoni merged 3 commits into
mainfrom
perf/promise-proxy-thread-check
Nov 26, 2026
Merged

edusperoni merged 3 commits into
mainfrom
perf/promise-proxy-thread-check

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

What

Several places decided "is this the runtime thread?" by comparing CFRunLoopGetCurrent() with a stored run loop. CFRunLoopGetCurrent() creates a run loop for any thread that lacks one, so every GCD / NSOperationQueue thread that hit one of these checks got a run loop allocated just to learn it wasn't the runtime thread. The Promise proxy was the worst case: it did this on every construct and every cross-thread settle. It also marshaled settlements with CFRunLoopPerformBlock, which meant converting each bound resolve/reject into an ObjC block and keeping a CFRunLoopRef wrapper per Promise.

Promise proxy

  • New binding isRuntimeThread(), which calls Runtime::IsOnRuntimeThread() (pthread_equal).
  • Settlements that need to reach the runtime thread go into a JS FIFO in the builtin (a head/tail node list, so user code can't patch it). The new binding postToRuntimeThread() posts a capture-free EventLoop::PostInternal entry for each one. On the runtime thread, each entry calls the builtin's exported runNext(), which runs exactly one queued settlement. A post refused at shutdown doesn't enqueue, so posts and queued settlements always pair 1:1. The exported function lives in a StateFor slot, and no v8::Global is created per post.
  • The builtin no longer calls CFRunLoopGetCurrent, CFRunLoopPerformBlock or CFRunLoopWakeUp.
  • Error handling follows fix(runtime): same error handling in Debug and Release #605 (Checks.h). Init failures (binding install, builtin run or export shape, state slot) are NS_CHECKs, not tns::Assert. A failed runNext call leaves its exception pending for the event loop entry, as the policy requires.

Behaviour changes (intended):

  • Settlements now run in common modes, the same as timers and other internal-lane work. Before, they ran in kCFRunLoopDefaultMode only, so a settlement from a background thread waited out UI tracking such as scrolling.
  • They run one per run-loop pass, each followed by the lane's microtask checkpoint. Performed blocks used to all drain in one pass. Ordering between settlements is unchanged (FIFO).

Other run-loop identity checks → thread checks

  • ClassBuilder.mm retain/release hooks and Runtime::GetNapiEnvIfAlive → Runtime::IsOnRuntimeThread().
  • NapiEnv / threadsafe functions now use a pthread_threadid_np ID. Unlike a pthread_t, it is never reused after the thread exits. That keeps napi_would_deadlock safe for producers that outlive the env's thread, so the tsfn no longer has to CFRetain the run loop.
  • Removed Runtime::RuntimeLoop(), NapiEnv::RuntimeLoop() and the RuntimeLoop() != nullptr guards in napi_create_threadsafe_function / napi_create_async_work. Those guards were vacuous because the loop was always set in the constructor.

The only CFRunLoopGetCurrent() calls left are home-thread captures at init (Runtime::Init, EventLoop::BindToCurrentThread, WorkerWrapper).

Testing

  • Full suite (./run_tests.sh --temp-sim): 0 failures, 2280 specs.
  • New spec: five runtime-thread promises are resolved or rejected back-to-back, in reverse order, from one background block. All of them settle on the runtime thread, in resolution order. This guards the post/queue pairing.
  • No spec checks that the run-loop allocation is gone, because there's no public way to test for a run loop without creating one.
  • napi_would_deadlock has no spec. napi_make_callback is only exercised from the env thread, so the off-thread rejection branch is not covered.

Summary by CodeRabbit

  • Bug Fixes
    • Promise fulfillment and rejection handlers now run on the runtime thread when settled from a background thread, preserving reliable callback execution.
    • Thread-safe callbacks and asynchronous work no longer depend on run-loop availability.
  • Tests
    • Added coverage for background promise settlements, handler thread affinity, and completion order.

…mise proxy

The Promise proxy decided whether to marshal a settlement by comparing
CFRunLoopGetCurrent() against the runtime loop, both when a Promise was
constructed and when it settled. CFRunLoopGetCurrent() creates a run loop
for any thread that has none, so every GCD/NSOperationQueue thread that
created or settled a Promise got a run loop allocated just to learn it was
not the runtime thread.

The binding now exposes isRuntimeThread() (pthread_equal against the
runtime thread, captured alongside the runtime loop), and the builtin only
calls CFRunLoopGetCurrent() on the runtime thread, once per isolate.
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The runtime replaces CoreFoundation run-loop checks with thread identity checks. PromiseProxy adds a FIFO queue for off-thread settlements and posts dispatch work through the runtime event loop. N-API and runtime call sites also use thread identity checks.

Changes: Runtime Thread Identity and Promise Scheduling

Layer / File(s) Summary
Runtime thread identity
NativeScript/napi/NapiEnv.h, NativeScript/napi/NapiEnv.mm, NativeScript/runtime/Runtime.h
NapiEnv records its thread ID and provides methods to check thread identity. Runtime removes its RuntimeLoop() accessor.
Thread checks and event-loop dispatch
NativeScript/napi/NapiThreadSafeFunction.mm, NativeScript/napi/NodeApiEmbed.mm, NativeScript/runtime/ClassBuilder.mm, NativeScript/runtime/Runtime.mm
N-API and runtime code replace run-loop comparisons with thread identity checks. Thread-safe functions use the environment thread ID for deadlock checks and retain event-loop dispatch.
Promise settlement queue
NativeScript/runtime/PromiseProxy.cpp, NativeScript/runtime/js/promise-proxy.js, TestRunner/app/tests/Promises.js
PromiseProxy exposes runtime-thread checks and event-loop posting. The JavaScript proxy queues off-thread settlements and exports runNext for dispatch. The new test checks handler thread and settlement order.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant PromiseProxy
  participant RuntimeBinding
  participant EventLoop
  PromiseProxy->>RuntimeBinding: Check runtime-thread status
  RuntimeBinding-->>PromiseProxy: Return thread status
  PromiseProxy->>EventLoop: Post settlement task
  EventLoop->>PromiseProxy: Invoke runNext
  PromiseProxy->>PromiseProxy: Process next queued settlement
Loading

Possibly related issues

Suggested reviewers: nathanwalker, adrian-niculescu, darind

Merge Risk: Minimal · up to 486ac

This change replaces run-loop identity checks with thread identity checks. It also routes off-thread Promise settlements through a FIFO queue and the runtime event loop. No concrete defect was identified, and the author reports 0 failures across 2280 specs. Merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: Promise settlement moves through the event loop, and identity checks move from run loops to thread checks. The title is concise and specific. The 'perf' prefix describ…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: Promise settlement moves through the event loop, and identity checks move from run loops to thread checks. The title is concise and specific. The 'perf' prefix describes the purpose as performance, which the PR objectives do not state as a measured result, but the title still matches the changeset's primary intent.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the runtime thread,
Then queues a task where paths are led.
The event loop hops, the callbacks flow,
In first-in, first-out order they go.
Five promises settle, each in its place,
While bunny ears keep time and pace.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 19067017-8c55-4191-a05e-1d26a5d51161
Commits

Reviewing files that changed from the base of the PR and between 231ab09 and 486ac42.

Files selected for processing: 10

  • NativeScript/napi/NapiEnv.h
  • NativeScript/napi/NapiEnv.mm
  • NativeScript/napi/NapiThreadSafeFunction.mm
  • NativeScript/napi/NodeApiEmbed.mm
  • NativeScript/runtime/ClassBuilder.mm
  • NativeScript/runtime/PromiseProxy.cpp
  • NativeScript/runtime/Runtime.h
  • NativeScript/runtime/Runtime.mm
  • NativeScript/runtime/js/promise-proxy.js
  • TestRunner/app/tests/Promises.js
Files with no reviewable changes: 1

  • NativeScript/runtime/Runtime.h

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

…over run-loop checks

The Promise proxy marshaled runtime-thread settlements with
CFRunLoopPerformBlock, which converted every bound resolve/reject into an
ObjC block and kept a CFRunLoopRef wrapper per Promise. The builtin now
queues settlements in a JS FIFO, and a native postToRuntimeThread() posts
a capture-free internal-lane entry per settlement that runs the oldest one
on the runtime thread. The builtin no longer touches CFRunLoop at all.

Settlements now run in common modes (during UI tracking too), one per
run-loop pass, each followed by the lane's microtask checkpoint.

The other "is this the runtime thread" checks that compared
CFRunLoopGetCurrent() against a stored loop are now thread checks too:
ClassBuilder's retain/release hooks and GetNapiEnvIfAlive use
Runtime::IsOnRuntimeThread(), and NapiEnv/threadsafe functions use a
pthread_threadid_np id, which is never reused, so the tsfn no longer
retains the run loop to keep its identity stable. Runtime::RuntimeLoop()
and NapiEnv::RuntimeLoop() are gone, along with the vacuous
RuntimeLoop() != nullptr guards.
@edusperoni edusperoni changed the title perf(runtime): check the runtime thread, not its run loop, in the Promise proxy perf(runtime): settle Promises through the event loop; check threads, not run loops Nov 26, 2026
@edusperoni
edusperoni merged commit 382df51 into main Nov 26, 2026
14 checks passed
@edusperoni
edusperoni deleted the perf/promise-proxy-thread-check branch November 26, 2026 21:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant