From 6319f7503a8351d70c0c7c0a0c9bee79e77a4942 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 19 Nov 2026 16:58:31 -0300 Subject: [PATCH 1/3] fix(runtime): keep JS timers in fire-date order with foreign runloop timers Every ordered-lane token (setTimeout, setInterval, __ns__queueMacrotask) shared one CFRunLoopTimer, re-armed to the earliest pending token after each fire, post and cancel. CF clamps a past fire date to now, so once the earliest token was overdue, any re-arm moved the lane behind every overdue foreign NSTimer, including ones due later. An earlier overdue item, or a setTimeout/clearTimeout in the window, was enough to run a 25 ms NSTimer before a 20 ms JS timer; this is the intermittent ASan failure of "interleaves with foreign NSTimer timeouts by due time". Each token now owns a CFRunLoopTimer armed at its own due time and never re-armed after it is due; consuming or cancelling a token invalidates its timer. The timer context is refcounted through CF's retain/release so a cancel from another thread cannot free it under a running callout. Ordered tasks still never nest: a token that fires in a runloop spun from inside one is parked and re-armed when that task returns. Several overdue tokens now fire within one CF timer pass, interleaved with foreign timers by fire date, instead of one per runloop pass. Self-rescheduling chains still yield every step. --- NativeScript/runtime/EventLoop.h | 46 ++++--- NativeScript/runtime/EventLoop.mm | 147 +++++++++++++++------ TestRunner/app/tests/CreateRequireTests.js | 13 +- TestRunner/app/tests/EventLoopTests.js | 66 +++++++++ 4 files changed, 205 insertions(+), 67 deletions(-) diff --git a/NativeScript/runtime/EventLoop.h b/NativeScript/runtime/EventLoop.h index 3dd7598f9..725c74663 100644 --- a/NativeScript/runtime/EventLoop.h +++ b/NativeScript/runtime/EventLoop.h @@ -8,7 +8,6 @@ #include #include #include -#include #include #include "Common.h" @@ -45,14 +44,19 @@ class OrderedTaskSource { * * Ordered lane - work whose ordering is observable against other app-level * runloop work (spec'd macrotasks, JS timers). Every post is an anonymous - * "task due" token on ONE CFRunLoopTimer armed at the earliest pending due - * time (a due-now token gets a past fire date and fires on the next pass), so - * tokens stay in fire-date order with foreign NSTimers and each fire yields a - * full runloop pass - performed-block delivery would be sooner but a - * self-rescheduling chain of blocks starves the before-waiting phase (CA - * rendering, autorelease pool, the rejection drain). Each token runs the - * earliest due item across the ordered entries and the OrderedTaskSource - * (Timers) - one due-ordered domain, and a leftover token is a cheap no-op. + * "task due" token with its own CFRunLoopTimer at the token's due time, + * never re-armed once that time has passed: CF clamps a past fire date to + * now, so such a timer would fall behind every overdue foreign NSTimer. + * Tokens therefore keep fire-date order with foreign timers even when + * several are overdue at once. Ordered tasks never nest: a token that fires + * in a runloop spun from inside one waits for it to return (losing its + * fire-date position only then). A due-now token still waits for the + * timer phase rather than riding a performed block: a self-rescheduling + * chain of blocks starves the before-waiting phase (CA rendering, autorelease + * pool, the rejection drain), while a timer created during a timer pass only + * fires on the next one. Each token runs the earliest due item across the + * ordered entries and the OrderedTaskSource (Timers) - one due-ordered + * domain, and a leftover token is a cheap no-op. * * Internal lane - work in its own ordering domain: v8 platform foreground * tasks (Atomics.waitAsync wakeups, GC tasks, streaming-compilation @@ -114,11 +118,11 @@ class EventLoop { double PostOrderedToken(double dueTimeMs); /** - * Removes one not-yet-matured ordered token at this due time, un-arming its - * wakeup. Returns false when no such token is pending - it already matured, - * so its slot cannot be recalled; the caller must leave a tombstone for it - * instead. Tokens are anonymous and counted, - * so cancelling one token plus one item keeps slots 1:1 no matter which + * Removes one not-yet-matured ordered token at this due time, invalidating + * its timer. Returns false when no such token is pending - it already + * matured, so its slot cannot be recalled; the caller must leave a + * tombstone for it instead. Tokens are anonymous and counted, so + * cancelling one token plus one item keeps slots 1:1 no matter which * producer's token is physically removed. */ bool TryCancelOrderedToken(double dueTimeMs); @@ -205,13 +209,13 @@ class EventLoop { static bool HasDueLocked(Lane& lane, double now); void SignalInternalLocked(); void ArmInternalTimerLocked(double now); - void ArmOrderedTimerLocked(double now); + void AddOrderedTokenLocked(double key, double now); void RunEntry(Entry& entry); void RunOneInternal(); static void InternalSourcePerform(void* info); static void InternalTimerFired(CFRunLoopTimerRef timer, void* info); - static void OrderedTimerFired(CFRunLoopTimerRef timer, void* info); + static void OrderedTokenFired(CFRunLoopTimerRef timer, void* info); v8::Isolate* isolate_; std::mutex mutex_; @@ -219,14 +223,18 @@ class EventLoop { Lane ordered_; // ordered-lane source with its own bookkeeping (Timers); home-thread only OrderedTaskSource* timerSource_ = nullptr; - // future-due ordered tokens awaiting orderedTimer_ - std::multiset pendingTokens_; + // pending ordered tokens by key, each owning its CFRunLoopTimer (+1) + std::multimap pendingTokens_; + // set while an ordered task runs; tokens that fire meanwhile (from a + // runloop the task spins) are parked, still in pendingTokens_, and + // re-armed when it returns + bool runningOrderedTask_ = false; + std::vector> parkedTokens_; // tokens posted before the bind; flushed by BindToCurrentThread std::vector bufferedTokens_; CFRunLoopRef loop_ = nullptr; CFRunLoopSourceRef internalSource_ = nullptr; CFRunLoopTimerRef internalTimer_ = nullptr; - CFRunLoopTimerRef orderedTimer_ = nullptr; bool stopped_ = false; }; diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index 9ca381ca3..a601c307d 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -1,6 +1,7 @@ #include "EventLoop.h" #include +#include #include #include @@ -32,6 +33,35 @@ void RunGuarded(F&& body) { } } +// Context of one ordered token's CFRunLoopTimer. Refcounted through the +// context's retain/release so CF holds a reference across each callout: +// CFRunLoopTimerInvalidate releases the context immediately, and a token may +// be cancelled from another thread while its callout is being dispatched. +struct OrderedTokenInfo { + OrderedTokenInfo(tns::EventLoop* loop, double key) : loop(loop), key(key) {} + tns::EventLoop* const loop; + const double key; + std::atomic refs{0}; +}; + +const void* RetainOrderedTokenInfo(const void* info) { + auto token = const_cast(static_cast(info)); + token->refs.fetch_add(1, std::memory_order_relaxed); + return info; +} + +void ReleaseOrderedTokenInfo(const void* info) { + auto token = const_cast(static_cast(info)); + if (token->refs.fetch_sub(1, std::memory_order_acq_rel) == 1) { + delete token; + } +} + +void DisposeTimer(CFRunLoopTimerRef timer) { + CFRunLoopTimerInvalidate(timer); + CFRelease(timer); +} + } // namespace namespace tns { @@ -68,10 +98,6 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + kNeverFireInterval, kNeverFireInterval, 0, 0, &EventLoop::InternalTimerFired, &timerContext); CFRunLoopAddTimer(loop_, internalTimer_, kCFRunLoopCommonModes); - orderedTimer_ = - CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + kNeverFireInterval, - kNeverFireInterval, 0, 0, &EventLoop::OrderedTimerFired, &timerContext); - CFRunLoopAddTimer(loop_, orderedTimer_, kCFRunLoopCommonModes); // flush work buffered before the home thread was known auto now = NowMs(); @@ -85,9 +111,8 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { auto tokens = std::move(bufferedTokens_); bufferedTokens_.clear(); for (double due : tokens) { - pendingTokens_.insert(due); + AddOrderedTokenLocked(due, now); } - ArmOrderedTimerLocked(now); } void EventLoop::Shutdown() { @@ -108,7 +133,11 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { droppedInternalDelayed.swap(internal_.delayed); droppedOrdered.swap(ordered_.immediate); droppedOrderedDelayed.swap(ordered_.delayed); + for (auto& token : pendingTokens_) { + DisposeTimer(token.second); + } pendingTokens_.clear(); + parkedTokens_.clear(); bufferedTokens_.clear(); if (internalSource_ != nullptr) { CFRunLoopSourceInvalidate(internalSource_); @@ -120,11 +149,6 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { CFRelease(internalTimer_); internalTimer_ = nullptr; } - if (orderedTimer_ != nullptr) { - CFRunLoopTimerInvalidate(orderedTimer_); - CFRelease(orderedTimer_); - orderedTimer_ = nullptr; - } loop_ = nullptr; } @@ -169,19 +193,31 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { return dueTimeMs; } // every token rides the timer phase, even due-now ones (a past fire date - // fires on the next runloop pass). Performed blocks would deliver sooner, + // fires on the next timer pass). Performed blocks would deliver sooner, // but a self-rescheduling chain of them never lets the loop reach its // before-waiting phase - starving CA rendering commits, the autorelease - // pool and the rejection drain - while a due timer still yields a full - // pass between fires. This also keeps due-now tokens in fire-date order - // with foreign NSTimers, like the per-timer CFRunLoopTimers this replaces. + // pool and the rejection drain. double key = std::max(dueTimeMs, now); - pendingTokens_.insert(key); - ArmOrderedTimerLocked(now); + AddOrderedTokenLocked(key, now); CFRunLoopWakeUp(loop_); return key; } +void EventLoop::AddOrderedTokenLocked(double key, double now) { + CFRunLoopTimerContext context = {0, new OrderedTokenInfo(this, key), &RetainOrderedTokenInfo, + &ReleaseOrderedTokenInfo, nullptr}; + // Not re-armed once it is due, except when parked by a nested runloop (see + // OrderedTokenFired): CF clamps a past fire date to now, which would move + // the token behind overdue foreign timers. Repeating with an unreachable + // interval only so its own callout can re-arm it - CF invalidates a + // one-shot timer after its callout. + CFRunLoopTimerRef timer = + CFRunLoopTimerCreate(kCFAllocatorDefault, FireDateFor(key, now), kNeverFireInterval, 0, 0, + &EventLoop::OrderedTokenFired, &context); + CFRunLoopAddTimer(loop_, timer, kCFRunLoopCommonModes); + pendingTokens_.emplace(key, timer); +} + bool EventLoop::PostInternal(std::function fn) { std::lock_guard lock(mutex_); if (stopped_) { @@ -249,8 +285,8 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { if (pendingIt == pendingTokens_.end()) { return false; } + DisposeTimer(pendingIt->second); pendingTokens_.erase(pendingIt); - ArmOrderedTimerLocked(NowMs()); return true; } @@ -339,15 +375,6 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { due >= 0 ? FireDateFor(due, now) : CFAbsoluteTimeGetCurrent() + kNeverFireInterval); } -void EventLoop::ArmOrderedTimerLocked(double now) { - if (orderedTimer_ == nullptr) { - return; - } - CFRunLoopTimerSetNextFireDate( - orderedTimer_, !pendingTokens_.empty() ? FireDateFor(*pendingTokens_.begin(), now) - : CFAbsoluteTimeGetCurrent() + kNeverFireInterval); -} - void EventLoop::RunEntry(Entry& entry) { if (entry.bare) { // the fn does its own ceremony - it may lock a different isolate, or @@ -483,27 +510,65 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { self->ArmInternalTimerLocked(now); } -void EventLoop::OrderedTimerFired(CFRunLoopTimerRef timer, void* info) { - auto self = static_cast(info); - bool due = false; +void EventLoop::OrderedTokenFired(CFRunLoopTimerRef timer, void* info) { + auto token = static_cast(info); + auto self = token->loop; { std::lock_guard lock(self->mutex_); if (self->stopped_) { return; } auto now = NowMs(); - if (!self->pendingTokens_.empty() && *self->pendingTokens_.begin() <= now) { - self->pendingTokens_.erase(self->pendingTokens_.begin()); - due = true; + if (token->key > now) { + // fired ahead of its CLOCK_MONOTONIC due time; still in the future, so + // CF honors the new date + CFRunLoopTimerSetNextFireDate(timer, FireDateFor(token->key, now)); + return; } - // one matured token per fire: re-arming with an already-past due time - // fires again on the next runloop pass, so foreign timers and blocks due - // between two matured tokens interleave instead of waiting out a batch - self->ArmOrderedTimerLocked(now); - } - if (due) { - self->RunOrderedTask(); - } + auto range = self->pendingTokens_.equal_range(token->key); + auto it = std::find_if(range.first, range.second, + [timer](const auto& entry) { return entry.second == timer; }); + if (it == range.second) { + // recalled by TryCancelOrderedToken while this fire was being dispatched + return; + } + if (self->runningOrderedTask_) { + // a runloop spun from inside an ordered task (a pumped require, app + // code): ordered tasks never nest, so the token waits for that task + CFRunLoopTimerSetNextFireDate(timer, CFAbsoluteTimeGetCurrent() + kNeverFireInterval); + self->parkedTokens_.emplace_back(token->key, timer); + return; + } + self->pendingTokens_.erase(it); + DisposeTimer(timer); + self->runningOrderedTask_ = true; + } + + struct UnparkOnExit { + EventLoop* self; + ~UnparkOnExit() { + std::lock_guard lock(self->mutex_); + self->runningOrderedTask_ = false; + auto parked = std::move(self->parkedTokens_); + self->parkedTokens_.clear(); + if (self->stopped_) { + return; + } + auto now = NowMs(); + for (auto& [key, timer] : parked) { + // only timers still owned by pendingTokens_; a parked token may have + // been cancelled (and its timer freed) meanwhile + auto range = self->pendingTokens_.equal_range(key); + for (auto it = range.first; it != range.second; ++it) { + if (it->second == timer) { + CFRunLoopTimerSetNextFireDate(timer, FireDateFor(key, now)); + break; + } + } + } + } + } unpark{self}; + self->RunOrderedTask(); } } // namespace tns diff --git a/TestRunner/app/tests/CreateRequireTests.js b/TestRunner/app/tests/CreateRequireTests.js index 68d418456..91e704120 100644 --- a/TestRunner/app/tests/CreateRequireTests.js +++ b/TestRunner/app/tests/CreateRequireTests.js @@ -256,13 +256,12 @@ describe("createRequire", function () { }, 0); }); - // Entered from a main-queue block, not from a timer callback: JS - // timers ride ONE shared CFRunLoopTimer, and a CFRunLoopTimer does - // not re-enter, so a require started from inside that timer's own - // callback can never let another timer fire no matter how the loop - // is pumped. From a runloop block the timer is free to fire, which - // is what makes this a test of pumpRunLoop rather than of - // re-entrancy. + // Entered from a main-queue block, not from a timer callback: + // ordered tasks (JS timers, macrotasks) never nest, so a require + // started from inside a timer callback can never let another + // timer fire no matter how the loop is pumped. From a runloop + // block the timer is free to fire, which is what makes this a + // test of pumpRunLoop rather than of re-entrancy. function onFreshTask(fn) { NSOperationQueue.mainQueue.addOperationWithBlock(fn); } diff --git a/TestRunner/app/tests/EventLoopTests.js b/TestRunner/app/tests/EventLoopTests.js index cb5ec2426..24ae133c4 100644 --- a/TestRunner/app/tests/EventLoopTests.js +++ b/TestRunner/app/tests/EventLoopTests.js @@ -165,6 +165,72 @@ describe("event loop ordered macrotasks", function () { done(); }, 30); }); + + // CF clamps a past fire date to now, so re-arming a matured token's timer + // would land it behind every overdue foreign timer. Each case makes ns20 + // and nstimer25 overdue together and disturbs the ordered lane in a + // different way. + function expectDueOrderAfterBusyWait(order, expected, afterBusyWait, done) { + __ns__setTimeout(() => order.push("ns20"), 20); + foreignSetTimeout(() => order.push("nstimer25"), 25); + __ns__setTimeout(() => order.push("ns30"), 30); + const start = Date.now(); + while (Date.now() - start < 45) { } + if (afterBusyWait) { + afterBusyWait(); + } + foreignSetTimeout(() => { + expect(order).toEqual(expected); + done(); + }, 30); + } + + it("keeps due-time order with foreign timers behind an earlier overdue timer", function (done) { + const order = []; + __ns__setTimeout(() => order.push("ns10"), 10); + expectDueOrderAfterBusyWait(order, ["ns10", "ns20", "nstimer25", "ns30"], null, done); + }); + + it("keeps due-time order with foreign timers behind an earlier macrotask", function (done) { + const order = []; + __ns__queueMacrotask(() => order.push("macro")); + expectDueOrderAfterBusyWait(order, ["macro", "ns20", "nstimer25", "ns30"], null, done); + }); + + it("keeps due-time order with foreign timers when a timer is scheduled after they matured", function (done) { + const order = []; + let late; + expectDueOrderAfterBusyWait(order, ["ns20", "nstimer25", "ns30"], () => { + late = __ns__setTimeout(() => order.push("late"), 1000); + }, () => { + __ns__clearTimeout(late); + done(); + }); + }); + + // A runloop spun from inside a timer callback (a pumped require, app code) + // must not run other ordered tasks nested inside it. + it("does not run ordered tasks inside a runloop spun from a timer callback", function (done) { + __ns__setTimeout(() => { + const order = []; + __ns__setTimeout(() => order.push("timer"), 0); + __ns__queueMacrotask(() => order.push("macro")); + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, false); + expect(order).toEqual([]); + __ns__setTimeout(() => { + expect(order).toEqual(["timer", "macro"]); + done(); + }, 0); + }, 0); + }); + + it("keeps due-time order with foreign timers when a timer is cleared after they matured", function (done) { + const order = []; + const unrelated = __ns__setTimeout(() => order.push("cleared"), 1000); + expectDueOrderAfterBusyWait(order, ["ns20", "nstimer25", "ns30"], () => { + __ns__clearTimeout(unrelated); + }, done); + }); }); // A self-rescheduling immediate timer must not starve the rest of the From adb56c393244daa83dbf54ad08d396f06d77e695 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 19 Nov 2026 17:48:07 -0300 Subject: [PATCH 2/3] fix(runtime): report rejections per task and keep ordered tokens on one clock Unhandled rejections were reported only from a kCFRunLoopBeforeWaiting observer, which runs at most once per runloop pass and not at all on passes that handled a source. With overdue timers now firing together in one CF timer pass, a second timer could attach a handler and suppress the first timer's unhandledrejection; consecutive internal-lane entries and messages delivered in one port drain had the same gap. The tracker is now drained after each ordered task, each non-bare internal entry and each port message - Node's model, deterministic where HTML only queues the notification as a task. The observer stays for JS entered from outside the event loop. Ordered-token keys were CLOCK_MONOTONIC, which keeps counting through system sleep, while each token's CFRunLoopTimer is armed once on mach_absolute_time, which does not. After a wake a fresh timer could run an older, now-due timer's item and then wait out that timer's remaining delay. EventLoop and Timers now both use CLOCK_UPTIME_RAW, so pending timers pause during sleep like NSTimers. Each ordered task also runs in its own autorelease pool, since a batch of overdue tasks no longer gets a runloop pass - and the runloop's pool boundary - between tasks. --- NativeScript/runtime/EventLoop.h | 7 ++- NativeScript/runtime/EventLoop.mm | 31 ++++++++-- NativeScript/runtime/Messaging.cpp | 4 +- NativeScript/runtime/NativeScriptException.h | 8 +++ NativeScript/runtime/NativeScriptException.mm | 18 ++++++ NativeScript/runtime/Runtime.mm | 23 ++----- NativeScript/runtime/Timers.cpp | 3 +- TestRunner/app/tests/EventLoopTests.js | 61 +++++++++++++++++++ 8 files changed, 127 insertions(+), 28 deletions(-) diff --git a/NativeScript/runtime/EventLoop.h b/NativeScript/runtime/EventLoop.h index 725c74663..d376c0b81 100644 --- a/NativeScript/runtime/EventLoop.h +++ b/NativeScript/runtime/EventLoop.h @@ -107,8 +107,8 @@ class EventLoop { bool PostOrderedDelayed(std::function fn, double delayMs); /** - * Posts a bare ordered token due at an absolute CLOCK_MONOTONIC time - * (NowMs() units) for an item the OrderedTaskSource keeps in its own + * Posts a bare ordered token due at an absolute NowMs() time + * (CLOCK_UPTIME_RAW milliseconds) for an item the OrderedTaskSource keeps in its own * bookkeeping (Timers). One token per item; the drain picks the earliest * due item across the source and the ordered entries, so the token needn't * name what it will run. Returns the key actually recorded (an overdue due @@ -177,7 +177,8 @@ class EventLoop { */ void RunOrderedTask(); - // CLOCK_MONOTONIC milliseconds - the clock every due time and token is on + // CLOCK_UPTIME_RAW milliseconds - the clock every due time and token is on; + // it pauses during system sleep, like the CFRunLoopTimers tokens ride static double NowMs(); private: diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index a601c307d..8e14026c2 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -67,12 +67,16 @@ void DisposeTimer(CFRunLoopTimerRef timer) { namespace tns { double EventLoop::NowMs() { + // mach_absolute_time's clock, the one CFRunLoopTimers fire on: a token's + // timer is armed once, so a key on a clock that keeps counting through + // sleep (CLOCK_MONOTONIC) would disagree with its timer after a wake and + // hand newer timers an older timer's far-off token struct timespec res; - clock_gettime(CLOCK_MONOTONIC, &res); + clock_gettime(CLOCK_UPTIME_RAW, &res); return 1000.0 * res.tv_sec + (double)res.tv_nsec / 1e6; } -// converts a CLOCK_MONOTONIC due time to a CFRunLoopTimer fire date. The two +// converts a NowMs() due time to a CFRunLoopTimer fire date. The two // clocks can drift (CFAbsoluteTime is wall-based), so consumers must treat a // fire as "check what is due now", never as proof a specific item is due. static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { @@ -429,7 +433,10 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { RunEntry(*entry); return; } - RunGuarded([&] { RunEntry(*entry); }); + RunGuarded([&] { + RunEntry(*entry); + PromiseRejectionTracker::DrainIfPending(isolate_); + }); } void EventLoop::RunNestableV8Tasks() { @@ -520,8 +527,8 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { } auto now = NowMs(); if (token->key > now) { - // fired ahead of its CLOCK_MONOTONIC due time; still in the future, so - // CF honors the new date + // fired ahead of its NowMs() due time; still in the future, so CF + // honors the new date CFRunLoopTimerSetNextFireDate(timer, FireDateFor(token->key, now)); return; } @@ -568,7 +575,19 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { } } } unpark{self}; - self->RunOrderedTask(); + // Overdue tokens fire back to back within one CF timer pass, so the + // runloop's own pool would span the whole batch; each task gets its own. + @autoreleasepool { + self->RunOrderedTask(); + bool stopped; + { + std::lock_guard lock(self->mutex_); + stopped = self->stopped_; + } + if (!stopped) { + RunGuarded([&] { PromiseRejectionTracker::DrainIfPending(self->isolate_); }); + } + } } } // namespace tns diff --git a/NativeScript/runtime/Messaging.cpp b/NativeScript/runtime/Messaging.cpp index 4163be09b..2477e1d58 100644 --- a/NativeScript/runtime/Messaging.cpp +++ b/NativeScript/runtime/Messaging.cpp @@ -739,8 +739,10 @@ void NativeMessagePort::Drain() { break; } // Per message, not per drain: a handler's microtasks run before the next - // message arrives, which is what both browsers and Node observe. + // message arrives, which is what both browsers and Node observe - and a + // rejection it leaves unhandled is reported before the next handler runs. isolate->PerformMicrotaskCheckpoint(); + PromiseRejectionTracker::DrainIfPending(isolate); } if (reschedule && this->data_ != nullptr) { diff --git a/NativeScript/runtime/NativeScriptException.h b/NativeScript/runtime/NativeScriptException.h index 9928fcdb2..a75502d68 100644 --- a/NativeScript/runtime/NativeScriptException.h +++ b/NativeScript/runtime/NativeScriptException.h @@ -128,6 +128,14 @@ class PromiseRejectionTracker { void OnReject(v8::Local promise, v8::Local reason); void OnHandlerAdded(v8::Local promise); void Drain(v8::Local context); + // Drains the isolate's tracker when it has work, taking the Locker and + // entering the main context. Runs after every event-loop task and port + // message, Node's model (rejections processed after each callback): a + // rejection left unhandled by one task is reported before the next task + // can attach a handler. HTML is looser - it queues the notification as a + // task that re-checks the promise - so this is the deterministic choice. + // Isolate's own thread only. + static void DrainIfPending(v8::Isolate* isolate); // Safe to call without holding the isolate lock: OnReject can run on any // thread that holds the v8::Locker (e.g. a background-thread rejection), so // the runloop observer polls this atomic instead of touching pending_. diff --git a/NativeScript/runtime/NativeScriptException.mm b/NativeScript/runtime/NativeScriptException.mm index ee29e0ac1..5e5db0121 100644 --- a/NativeScript/runtime/NativeScriptException.mm +++ b/NativeScript/runtime/NativeScriptException.mm @@ -598,6 +598,24 @@ static bool GiveWorkerOnErrorAChance(Isolate* isolate, Local context, L return !result.IsEmpty() && result->BooleanValue(isolate); } +void PromiseRejectionTracker::DrainIfPending(Isolate* isolate) { + auto cache = Caches::Get(isolate); + // HasPending is an atomic read: OnReject can run on any thread holding the + // v8::Locker, so pending_ itself must only be touched under the lock below. + // The event loop runs v8 tasks before Runtime::Init creates the context. + if (cache == nullptr || !cache->IsValid() || !cache->HasContext() || + cache->PromiseRejections == nullptr || !cache->PromiseRejections->HasPending()) { + return; + } + + v8::Locker locker(isolate); + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = cache->GetContext(); + Context::Scope context_scope(context); + cache->PromiseRejections->Drain(context); +} + void PromiseRejectionTracker::Drain(Local context) { if (draining_) { return; diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 58da09427..e60a35abb 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -510,9 +510,11 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { Local context = Context::New(isolate, nullptr, globalTemplate); context->Enter(); - // Drain tracked unhandled promise rejections once per runloop turn, just - // before the loop sleeps. The info pointer is the isolate; the callback - // re-validates liveness because the isolate may be torn down between turns. + // The event loop drains tracked unhandled promise rejections after each of + // its tasks; this observer catches rejections from JS entered any other way + // (native callbacks, NSTimer blocks) once per runloop turn, just before the + // loop sleeps. The info pointer is the isolate; the callback re-validates + // liveness because the isolate may be torn down between turns. CFRunLoopObserverContext observerContext = {0, isolate, nullptr, nullptr, nullptr}; rejectionObserver_ = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, /*repeats*/ true, @@ -808,20 +810,7 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { if (!Runtime::IsAlive(isolate)) { return; } - auto cache = Caches::Get(isolate); - // HasPending is an atomic read: OnReject can run on any thread holding the - // v8::Locker, so pending_ itself must only be touched under the lock below. - if (!cache->IsValid() || cache->PromiseRejections == nullptr || - !cache->PromiseRejections->HasPending()) { - return; - } - - v8::Locker locker(isolate); - Isolate::Scope isolate_scope(isolate); - HandleScope handle_scope(isolate); - Local context = cache->GetContext(); - Context::Scope context_scope(context); - cache->PromiseRejections->Drain(context); + PromiseRejectionTracker::DrainIfPending(isolate); } bool Runtime::IsAlive(const Isolate* isolate) { diff --git a/NativeScript/runtime/Timers.cpp b/NativeScript/runtime/Timers.cpp index 353fd5876..7597d2d67 100644 --- a/NativeScript/runtime/Timers.cpp +++ b/NativeScript/runtime/Timers.cpp @@ -55,9 +55,10 @@ inline static double ToMaybePositiveValue(const v8::Local& v, return value; } +// must match EventLoop::NowMs: due times become ordered-token keys static double now_ms() { struct timespec res; - clock_gettime(CLOCK_MONOTONIC, &res); + clock_gettime(CLOCK_UPTIME_RAW, &res); return 1000.0 * res.tv_sec + (double)res.tv_nsec / 1e6; } diff --git a/TestRunner/app/tests/EventLoopTests.js b/TestRunner/app/tests/EventLoopTests.js index 24ae133c4..4ea1a09e7 100644 --- a/TestRunner/app/tests/EventLoopTests.js +++ b/TestRunner/app/tests/EventLoopTests.js @@ -233,6 +233,67 @@ describe("event loop ordered macrotasks", function () { }); }); +// A rejection a task leaves unhandled is reported before the next task runs, +// Node's model (rejections processed after each callback), even when both +// tasks were due in the same runloop pass or arrive in one port drain. A +// later task attaching a handler then gets rejectionhandled, not silence. +describe("event loop unhandled rejections", function () { + // schedule(reject, handle) queues two tasks and may return a cleanup + function expectReportedBeforeNextTask(schedule) { + return raisesGlobalErrors(function (done) { + const events = []; + const onUnhandled = (e) => { + e.preventDefault(); + events.push("unhandled"); + }; + const onHandled = () => events.push("handled"); + global.addEventListener("unhandledrejection", onUnhandled); + global.addEventListener("rejectionhandled", onHandled); + let rejected; + const cleanup = schedule(() => { + rejected = Promise.reject(new Error("reported before the next task")); + events.push("reject"); + }, () => { + rejected.catch(() => { }); + events.push("handle"); + }); + foreignSetTimeout(() => { + global.removeEventListener("unhandledrejection", onUnhandled); + global.removeEventListener("rejectionhandled", onHandled); + if (cleanup) { + cleanup(); + } + expect(events).toEqual(["reject", "unhandled", "handle", "handled"]); + done(); + }, 100); + }); + } + + it("reports before a timer due in the same pass attaches a handler", + expectReportedBeforeNextTask((reject, handle) => { + __ns__setTimeout(reject, 0); + __ns__setTimeout(handle, 0); + })); + + it("reports before a macrotask due in the same pass attaches a handler", + expectReportedBeforeNextTask((reject, handle) => { + __ns__setTimeout(reject, 0); + __ns__queueMacrotask(handle); + })); + + it("reports before the next message on the same port attaches a handler", + expectReportedBeforeNextTask((reject, handle) => { + const channel = new MessageChannel(); + channel.port2.onmessage = (event) => (event.data === "reject" ? reject : handle)(); + channel.port1.postMessage("reject"); + channel.port1.postMessage("handle"); + return () => { + channel.port1.close(); + channel.port2.close(); + }; + })); +}); + // A self-rescheduling immediate timer must not starve the rest of the // runloop: foreign timers, the GCD main queue and the before-waiting phase // all have to keep running between steps. The before-waiting probe is the From b282a9b4da735a6c764e310f20b67b360db3b29b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 19 Nov 2026 18:48:54 -0300 Subject: [PATCH 3/3] feat(runtime): keep one timer per runloop pass by default, exact ordering behind NS_EXACT_TIMER_ORDERING Per-token CFRunLoopTimers keep exact fire-date order with foreign timers but run matured JS timers back to back in one CF timer pass, so several pending setTimeout(fn, 0) calls no longer yield to native work between them, and CF's per-mode timer arrays make every timer operation and runloop pass O(pending timers). The default build goes back to one shared CFRunLoopTimer that consumes one token per fire, and no longer re-arms it while the earliest token is unchanged, so posting or cancelling later work cannot push a matured timer behind overdue NSTimers. Per-token timers stay available with NS_EXACT_TIMER_ORDERING=1, together with the clock, refcounted context, parking and per-task pool they need. Unhandled rejections are still reported after every ordered task in both builds. The two specs that need exact ordering with several matured timers are skipped by default. --- NativeScript/runtime/EventLoop.h | 80 ++++++++++++------ NativeScript/runtime/EventLoop.mm | 108 ++++++++++++++++++++++--- NativeScript/runtime/Timers.cpp | 8 +- TestRunner/app/tests/EventLoopTests.js | 12 ++- 4 files changed, 165 insertions(+), 43 deletions(-) diff --git a/NativeScript/runtime/EventLoop.h b/NativeScript/runtime/EventLoop.h index d376c0b81..fc36a0264 100644 --- a/NativeScript/runtime/EventLoop.h +++ b/NativeScript/runtime/EventLoop.h @@ -5,14 +5,23 @@ #include #include +#include #include #include #include +#include #include #include "Common.h" #include "v8-platform.h" +// 1: JS timers keep exact fire-date order with foreign runloop timers at the +// cost of O(pending timers) per timer operation and no yielding between +// matured timers (see EventLoop's ordered lane). +#ifndef NS_EXACT_TIMER_ORDERING +#define NS_EXACT_TIMER_ORDERING 0 +#endif + namespace tns { /** @@ -44,19 +53,29 @@ class OrderedTaskSource { * * Ordered lane - work whose ordering is observable against other app-level * runloop work (spec'd macrotasks, JS timers). Every post is an anonymous - * "task due" token with its own CFRunLoopTimer at the token's due time, - * never re-armed once that time has passed: CF clamps a past fire date to - * now, so such a timer would fall behind every overdue foreign NSTimer. - * Tokens therefore keep fire-date order with foreign timers even when - * several are overdue at once. Ordered tasks never nest: a token that fires - * in a runloop spun from inside one waits for it to return (losing its - * fire-date position only then). A due-now token still waits for the - * timer phase rather than riding a performed block: a self-rescheduling - * chain of blocks starves the before-waiting phase (CA rendering, autorelease - * pool, the rejection drain), while a timer created during a timer pass only - * fires on the next one. Each token runs the earliest due item across the + * "task due" token; each token runs the earliest due item across the * ordered entries and the OrderedTaskSource (Timers) - one due-ordered - * domain, and a leftover token is a cheap no-op. + * domain, and a leftover token is a cheap no-op. A due-now token still waits + * for the timer phase rather than riding a performed block: a + * self-rescheduling chain of blocks starves the before-waiting phase (CA + * rendering, autorelease pool, the rejection drain). Ordered tasks never + * nest, and every task is followed by an unhandled-rejection drain. + * + * By default every token rides ONE CFRunLoopTimer armed at the earliest + * pending token, and each fire consumes one token, so every matured token + * yields a full runloop pass to native work - setTimeout(fn, 0) is how apps + * yield to native. The timer is left alone while the earliest token is + * unchanged. Once it is re-armed for a matured token, CF clamps the fire + * date to now: the first matured token keeps its fire-date position against + * foreign NSTimers, later ones fall behind any that are already overdue. + * + * With NS_EXACT_TIMER_ORDERING each token owns a CFRunLoopTimer at its due + * time instead, never re-armed once that time has passed, so tokens keep + * fire-date order with foreign timers however many are overdue. In exchange + * every post, cancel and runloop pass costs O(pending timers) in CF, and + * matured tokens run back to back in one timer pass without yielding. A + * token that fires in a runloop spun from inside an ordered task waits for + * that task to return. * * Internal lane - work in its own ordering domain: v8 platform foreground * tasks (Atomics.waitAsync wakeups, GC tasks, streaming-compilation @@ -107,19 +126,18 @@ class EventLoop { bool PostOrderedDelayed(std::function fn, double delayMs); /** - * Posts a bare ordered token due at an absolute NowMs() time - * (CLOCK_UPTIME_RAW milliseconds) for an item the OrderedTaskSource keeps in its own - * bookkeeping (Timers). One token per item; the drain picks the earliest - * due item across the source and the ordered entries, so the token needn't - * name what it will run. Returns the key actually recorded (an overdue due - * time is clamped to now) - the value TryCancelOrderedToken must be given - * to recall this token. + * Posts a bare ordered token due at an absolute NowMs() time for an item + * the OrderedTaskSource keeps in its own bookkeeping (Timers). One token per + * item; the drain picks the earliest due item across the source and the + * ordered entries, so the token needn't name what it will run. Returns the + * key actually recorded (an overdue due time is clamped to now) - the value + * TryCancelOrderedToken must be given to recall this token. */ double PostOrderedToken(double dueTimeMs); /** - * Removes one not-yet-matured ordered token at this due time, invalidating - * its timer. Returns false when no such token is pending - it already + * Removes one not-yet-matured ordered token at this due time, un-arming + * its wakeup. Returns false when no such token is pending - it already * matured, so its slot cannot be recalled; the caller must leave a * tombstone for it instead. Tokens are anonymous and counted, so * cancelling one token plus one item keeps slots 1:1 no matter which @@ -177,8 +195,9 @@ class EventLoop { */ void RunOrderedTask(); - // CLOCK_UPTIME_RAW milliseconds - the clock every due time and token is on; - // it pauses during system sleep, like the CFRunLoopTimers tokens ride + // milliseconds on the clock every due time and token is on: CLOCK_MONOTONIC, + // or with NS_EXACT_TIMER_ORDERING CLOCK_UPTIME_RAW, which pauses during + // sleep like the CFRunLoopTimers those tokens are fixed on static double NowMs(); private: @@ -213,10 +232,17 @@ class EventLoop { void AddOrderedTokenLocked(double key, double now); void RunEntry(Entry& entry); void RunOneInternal(); + // reports what the ordered task just run left unhandled; mutex_ not held + void DrainRejectionsAfterOrderedTask(); static void InternalSourcePerform(void* info); static void InternalTimerFired(CFRunLoopTimerRef timer, void* info); +#if NS_EXACT_TIMER_ORDERING static void OrderedTokenFired(CFRunLoopTimerRef timer, void* info); +#else + void ArmOrderedTimerLocked(double now); + static void OrderedTimerFired(CFRunLoopTimerRef timer, void* info); +#endif v8::Isolate* isolate_; std::mutex mutex_; @@ -224,6 +250,7 @@ class EventLoop { Lane ordered_; // ordered-lane source with its own bookkeeping (Timers); home-thread only OrderedTaskSource* timerSource_ = nullptr; +#if NS_EXACT_TIMER_ORDERING // pending ordered tokens by key, each owning its CFRunLoopTimer (+1) std::multimap pendingTokens_; // set while an ordered task runs; tokens that fire meanwhile (from a @@ -231,6 +258,13 @@ class EventLoop { // re-armed when it returns bool runningOrderedTask_ = false; std::vector> parkedTokens_; +#else + // pending ordered tokens, all riding orderedTimer_ + std::multiset pendingTokens_; + CFRunLoopTimerRef orderedTimer_ = nullptr; + // the token key orderedTimer_ is armed for; NaN while disarmed or spent + double armedTokenKey_ = std::numeric_limits::quiet_NaN(); +#endif // tokens posted before the bind; flushed by BindToCurrentThread std::vector bufferedTokens_; CFRunLoopRef loop_ = nullptr; diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index 8e14026c2..c33c42168 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -33,6 +34,7 @@ void RunGuarded(F&& body) { } } +#if NS_EXACT_TIMER_ORDERING // Context of one ordered token's CFRunLoopTimer. Refcounted through the // context's retain/release so CF holds a reference across each callout: // CFRunLoopTimerInvalidate releases the context immediately, and a token may @@ -61,18 +63,23 @@ void DisposeTimer(CFRunLoopTimerRef timer) { CFRunLoopTimerInvalidate(timer); CFRelease(timer); } +#endif } // namespace namespace tns { double EventLoop::NowMs() { + struct timespec res; +#if NS_EXACT_TIMER_ORDERING // mach_absolute_time's clock, the one CFRunLoopTimers fire on: a token's // timer is armed once, so a key on a clock that keeps counting through // sleep (CLOCK_MONOTONIC) would disagree with its timer after a wake and // hand newer timers an older timer's far-off token - struct timespec res; clock_gettime(CLOCK_UPTIME_RAW, &res); +#else + clock_gettime(CLOCK_MONOTONIC, &res); +#endif return 1000.0 * res.tv_sec + (double)res.tv_nsec / 1e6; } @@ -102,6 +109,12 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + kNeverFireInterval, kNeverFireInterval, 0, 0, &EventLoop::InternalTimerFired, &timerContext); CFRunLoopAddTimer(loop_, internalTimer_, kCFRunLoopCommonModes); +#if !NS_EXACT_TIMER_ORDERING + orderedTimer_ = + CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + kNeverFireInterval, + kNeverFireInterval, 0, 0, &EventLoop::OrderedTimerFired, &timerContext); + CFRunLoopAddTimer(loop_, orderedTimer_, kCFRunLoopCommonModes); +#endif // flush work buffered before the home thread was known auto now = NowMs(); @@ -137,11 +150,19 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { droppedInternalDelayed.swap(internal_.delayed); droppedOrdered.swap(ordered_.immediate); droppedOrderedDelayed.swap(ordered_.delayed); +#if NS_EXACT_TIMER_ORDERING for (auto& token : pendingTokens_) { DisposeTimer(token.second); } - pendingTokens_.clear(); parkedTokens_.clear(); +#else + if (orderedTimer_ != nullptr) { + CFRunLoopTimerInvalidate(orderedTimer_); + CFRelease(orderedTimer_); + orderedTimer_ = nullptr; + } +#endif + pendingTokens_.clear(); bufferedTokens_.clear(); if (internalSource_ != nullptr) { CFRunLoopSourceInvalidate(internalSource_); @@ -207,6 +228,35 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { return key; } +#if !NS_EXACT_TIMER_ORDERING +void EventLoop::AddOrderedTokenLocked(double key, double now) { + pendingTokens_.insert(key); + ArmOrderedTimerLocked(now); +} + +void EventLoop::ArmOrderedTimerLocked(double now) { + if (orderedTimer_ == nullptr) { + return; + } + // Left alone while the earliest token is unchanged: re-arming for a matured + // token clamps its fire date to now (CF does as well), which would move it + // behind every overdue foreign timer. + if (pendingTokens_.empty()) { + if (std::isnan(armedTokenKey_)) { + return; + } + armedTokenKey_ = std::numeric_limits::quiet_NaN(); + CFRunLoopTimerSetNextFireDate(orderedTimer_, CFAbsoluteTimeGetCurrent() + kNeverFireInterval); + return; + } + double head = *pendingTokens_.begin(); + if (head == armedTokenKey_) { + return; + } + armedTokenKey_ = head; + CFRunLoopTimerSetNextFireDate(orderedTimer_, FireDateFor(head, now)); +} +#else void EventLoop::AddOrderedTokenLocked(double key, double now) { CFRunLoopTimerContext context = {0, new OrderedTokenInfo(this, key), &RetainOrderedTokenInfo, &ReleaseOrderedTokenInfo, nullptr}; @@ -221,6 +271,7 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { CFRunLoopAddTimer(loop_, timer, kCFRunLoopCommonModes); pendingTokens_.emplace(key, timer); } +#endif bool EventLoop::PostInternal(std::function fn) { std::lock_guard lock(mutex_); @@ -289,8 +340,13 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { if (pendingIt == pendingTokens_.end()) { return false; } +#if NS_EXACT_TIMER_ORDERING DisposeTimer(pendingIt->second); pendingTokens_.erase(pendingIt); +#else + pendingTokens_.erase(pendingIt); + ArmOrderedTimerLocked(NowMs()); +#endif return true; } @@ -517,6 +573,44 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { self->ArmInternalTimerLocked(now); } +void EventLoop::DrainRejectionsAfterOrderedTask() { + { + std::lock_guard lock(mutex_); + if (stopped_) { + return; + } + } + RunGuarded([&] { PromiseRejectionTracker::DrainIfPending(isolate_); }); +} + +#if !NS_EXACT_TIMER_ORDERING +void EventLoop::OrderedTimerFired(CFRunLoopTimerRef timer, void* info) { + auto self = static_cast(info); + bool due = false; + { + std::lock_guard lock(self->mutex_); + if (self->stopped_) { + return; + } + auto now = NowMs(); + if (!self->pendingTokens_.empty() && *self->pendingTokens_.begin() <= now) { + self->pendingTokens_.erase(self->pendingTokens_.begin()); + due = true; + } + // One matured token per fire: re-arming with an already-past due time + // fires again on the next runloop pass, so native work runs between two + // matured tokens instead of waiting out a batch. This fire spent the + // arming (CF moves a fired timer to its unreachable interval unless its + // callout re-arms it), so the re-arm is unconditional. + self->armedTokenKey_ = std::numeric_limits::quiet_NaN(); + self->ArmOrderedTimerLocked(now); + } + if (due) { + self->RunOrderedTask(); + self->DrainRejectionsAfterOrderedTask(); + } +} +#else void EventLoop::OrderedTokenFired(CFRunLoopTimerRef timer, void* info) { auto token = static_cast(info); auto self = token->loop; @@ -579,15 +673,9 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { // runloop's own pool would span the whole batch; each task gets its own. @autoreleasepool { self->RunOrderedTask(); - bool stopped; - { - std::lock_guard lock(self->mutex_); - stopped = self->stopped_; - } - if (!stopped) { - RunGuarded([&] { PromiseRejectionTracker::DrainIfPending(self->isolate_); }); - } + self->DrainRejectionsAfterOrderedTask(); } } +#endif } // namespace tns diff --git a/NativeScript/runtime/Timers.cpp b/NativeScript/runtime/Timers.cpp index 7597d2d67..fee7f9e6f 100644 --- a/NativeScript/runtime/Timers.cpp +++ b/NativeScript/runtime/Timers.cpp @@ -55,12 +55,8 @@ inline static double ToMaybePositiveValue(const v8::Local& v, return value; } -// must match EventLoop::NowMs: due times become ordered-token keys -static double now_ms() { - struct timespec res; - clock_gettime(CLOCK_UPTIME_RAW, &res); - return 1000.0 * res.tv_sec + (double)res.tv_nsec / 1e6; -} +// due times become ordered-token keys, so they share the EventLoop's clock +static double now_ms() { return tns::EventLoop::NowMs(); } namespace tns { diff --git a/TestRunner/app/tests/EventLoopTests.js b/TestRunner/app/tests/EventLoopTests.js index 4ea1a09e7..49aa9d781 100644 --- a/TestRunner/app/tests/EventLoopTests.js +++ b/TestRunner/app/tests/EventLoopTests.js @@ -166,8 +166,8 @@ describe("event loop ordered macrotasks", function () { }, 30); }); - // CF clamps a past fire date to now, so re-arming a matured token's timer - // would land it behind every overdue foreign timer. Each case makes ns20 + // CF clamps a past fire date to now, so re-arming the lane for a matured + // token lands it behind every overdue foreign timer. Each case makes ns20 // and nstimer25 overdue together and disturbs the ordered lane in a // different way. function expectDueOrderAfterBusyWait(order, expected, afterBusyWait, done) { @@ -185,13 +185,17 @@ describe("event loop ordered macrotasks", function () { }, 30); } - it("keeps due-time order with foreign timers behind an earlier overdue timer", function (done) { + // Two matured runtime timers ahead of a foreign one: the default build + // yields a runloop pass between matured timers (setTimeout(fn, 0) is how + // apps yield to native), so the second is re-armed after the foreign + // timer. Only a build with NS_EXACT_TIMER_ORDERING=1 passes these. + xit("keeps due-time order with foreign timers behind an earlier overdue timer", function (done) { const order = []; __ns__setTimeout(() => order.push("ns10"), 10); expectDueOrderAfterBusyWait(order, ["ns10", "ns20", "nstimer25", "ns30"], null, done); }); - it("keeps due-time order with foreign timers behind an earlier macrotask", function (done) { + xit("keeps due-time order with foreign timers behind an earlier macrotask", function (done) { const order = []; __ns__queueMacrotask(() => order.push("macro")); expectDueOrderAfterBusyWait(order, ["macro", "ns20", "nstimer25", "ns30"], null, done);