Skip to content

Commit afec0d7

Browse files
addaleaxMylesBorins
authored andcommitted
async_hooks: improve resource stack performance
Removes some of the performance overhead that came with `executionAsyncResource()` by using the JS resource array only as a cache for the values provided by C++. The fact that we now use an entry trampoline is used to pass the resource without requiring extra C++/JS boundary crossings, and the direct accesses to the JS resource array from C++ are removed in all fast paths. This particularly improves performance when async hooks are not being used. This is a continuation of #33575 and shares some of its code with it. ./node benchmark/compare.js --new ./node --old ./node-master --runs 30 --filter messageport worker | Rscript benchmark/compare.R [00:06:14|% 100| 1/1 files | 60/60 runs | 2/2 configs]: Done confidence improvement accuracy (*) (**) (***) worker/messageport.js n=1000000 payload='object' ** 12.64 % ±7.30% ±9.72% ±12.65% worker/messageport.js n=1000000 payload='string' * 11.08 % ±9.00% ±11.98% ±15.59% ./node benchmark/compare.js --new ./node --old ./node-master --runs 20 --filter async-resource-vs-destroy async_hooks | Rscript benchmark/compare.R [00:22:35|% 100| 1/1 files | 40/40 runs | 6/6 configs]: Done confidence improvement accuracy (*) async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='async' type='async-local-storage' benchmarker='autocannon' 1.60 % ±7.35% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='async' type='async-resource' benchmarker='autocannon' 6.05 % ±6.57% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='async' type='destroy' benchmarker='autocannon' * 8.27 % ±7.50% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='callbacks' type='async-local-storage' benchmarker='autocannon' 7.42 % ±8.22% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='callbacks' type='async-resource' benchmarker='autocannon' 4.33 % ±7.84% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='callbacks' type='destroy' benchmarker='autocannon' 5.96 % ±7.15% (**) (***) async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='async' type='async-local-storage' benchmarker='autocannon' ±9.84% ±12.94% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='async' type='async-resource' benchmarker='autocannon' ±8.81% ±11.60% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='async' type='destroy' benchmarker='autocannon' ±10.07% ±13.28% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='callbacks' type='async-local-storage' benchmarker='autocannon' ±11.01% ±14.48% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='callbacks' type='async-resource' benchmarker='autocannon' ±10.50% ±13.81% async_hooks/async-resource-vs-destroy.js n=1000000 duration=5 connections=500 path='/' asyncMethod='callbacks' type='destroy' benchmarker='autocannon' ±9.58% ±12.62% Refs: #33575 PR-URL: #34319 Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Gerhard Stöbich <[email protected]> Reviewed-By: Stephen Belanger <[email protected]>
1 parent a130771 commit afec0d7

File tree

7 files changed

+129
-44
lines changed

7 files changed

+129
-44
lines changed

lib/internal/async_hooks.js

+18-15
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ const {
5050
// each hook's after() callback.
5151
const {
5252
pushAsyncContext: pushAsyncContext_,
53-
popAsyncContext: popAsyncContext_
53+
popAsyncContext: popAsyncContext_,
54+
executionAsyncResource: executionAsyncResource_,
55+
clearAsyncIdStack,
5456
} = async_wrap;
5557
// For performance reasons, only track Promises when a hook is enabled.
5658
const { enablePromiseHook, disablePromiseHook } = async_wrap;
@@ -89,7 +91,8 @@ const { resource_symbol, owner_symbol } = internalBinding('symbols');
8991
// for a given step, that step can bail out early.
9092
const { kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve,
9193
kCheck, kExecutionAsyncId, kAsyncIdCounter, kTriggerAsyncId,
92-
kDefaultTriggerAsyncId, kStackLength } = async_wrap.constants;
94+
kDefaultTriggerAsyncId, kStackLength, kUsesExecutionAsyncResource
95+
} = async_wrap.constants;
9396

9497
const { async_id_symbol,
9598
trigger_async_id_symbol } = internalBinding('symbols');
@@ -111,7 +114,10 @@ function useDomainTrampoline(fn) {
111114
domain_cb = fn;
112115
}
113116

114-
function callbackTrampoline(asyncId, cb, ...args) {
117+
function callbackTrampoline(asyncId, resource, cb, ...args) {
118+
const index = async_hook_fields[kStackLength] - 1;
119+
execution_async_resources[index] = resource;
120+
115121
if (asyncId !== 0 && hasHooks(kBefore))
116122
emitBeforeNative(asyncId);
117123

@@ -126,6 +132,7 @@ function callbackTrampoline(asyncId, cb, ...args) {
126132
if (asyncId !== 0 && hasHooks(kAfter))
127133
emitAfterNative(asyncId);
128134

135+
execution_async_resources.pop();
129136
return result;
130137
}
131138

@@ -134,9 +141,15 @@ setCallbackTrampoline(callbackTrampoline);
134141
const topLevelResource = {};
135142

136143
function executionAsyncResource() {
144+
// Indicate to the native layer that this function is likely to be used,
145+
// in which case it will inform JS about the current async resource via
146+
// the trampoline above.
147+
async_hook_fields[kUsesExecutionAsyncResource] = 1;
148+
137149
const index = async_hook_fields[kStackLength] - 1;
138150
if (index === -1) return topLevelResource;
139-
const resource = execution_async_resources[index];
151+
const resource = execution_async_resources[index] ||
152+
executionAsyncResource_(index);
140153
return lookupPublicResource(resource);
141154
}
142155

@@ -478,16 +491,6 @@ function emitDestroyScript(asyncId) {
478491
}
479492

480493

481-
// Keep in sync with Environment::AsyncHooks::clear_async_id_stack
482-
// in src/env-inl.h.
483-
function clearAsyncIdStack() {
484-
async_id_fields[kExecutionAsyncId] = 0;
485-
async_id_fields[kTriggerAsyncId] = 0;
486-
async_hook_fields[kStackLength] = 0;
487-
execution_async_resources.splice(0, execution_async_resources.length);
488-
}
489-
490-
491494
function hasAsyncIdStack() {
492495
return hasHooks(kStackLength);
493496
}
@@ -497,7 +500,7 @@ function hasAsyncIdStack() {
497500
function pushAsyncContext(asyncId, triggerAsyncId, resource) {
498501
const offset = async_hook_fields[kStackLength];
499502
if (offset * 2 >= async_wrap.async_ids_stack.length)
500-
return pushAsyncContext_(asyncId, triggerAsyncId, resource);
503+
return pushAsyncContext_(asyncId, triggerAsyncId);
501504
async_wrap.async_ids_stack[offset * 2] = async_id_fields[kExecutionAsyncId];
502505
async_wrap.async_ids_stack[offset * 2 + 1] = async_id_fields[kTriggerAsyncId];
503506
execution_async_resources[offset] = resource;

lib/internal/process/execution.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -190,10 +190,10 @@ function createOnGlobalUncaughtException() {
190190
do {
191191
emitAfter(executionAsyncId());
192192
} while (hasAsyncIdStack());
193-
// Or completely empty the id stack.
194-
} else {
195-
clearAsyncIdStack();
196193
}
194+
// And completely empty the id stack, including anything that may be
195+
// cached on the native side.
196+
clearAsyncIdStack();
197197

198198
return true;
199199
};

src/api/callback.cc

+13-8
Original file line numberDiff line numberDiff line change
@@ -160,12 +160,16 @@ MaybeLocal<Value> InternalMakeCallback(Environment* env,
160160

161161
Local<Function> hook_cb = env->async_hooks_callback_trampoline();
162162
int flags = InternalCallbackScope::kNoFlags;
163-
int hook_count = 0;
163+
bool use_async_hooks_trampoline = false;
164+
AsyncHooks* async_hooks = env->async_hooks();
164165
if (!hook_cb.IsEmpty()) {
166+
// Use the callback trampoline if there are any before or after hooks, or
167+
// we can expect some kind of usage of async_hooks.executionAsyncResource().
165168
flags = InternalCallbackScope::kSkipAsyncHooks;
166-
AsyncHooks* async_hooks = env->async_hooks();
167-
hook_count = async_hooks->fields()[AsyncHooks::kBefore] +
168-
async_hooks->fields()[AsyncHooks::kAfter];
169+
use_async_hooks_trampoline =
170+
async_hooks->fields()[AsyncHooks::kBefore] +
171+
async_hooks->fields()[AsyncHooks::kAfter] +
172+
async_hooks->fields()[AsyncHooks::kUsesExecutionAsyncResource] > 0;
169173
}
170174

171175
InternalCallbackScope scope(env, resource, asyncContext, flags);
@@ -175,12 +179,13 @@ MaybeLocal<Value> InternalMakeCallback(Environment* env,
175179

176180
MaybeLocal<Value> ret;
177181

178-
if (hook_count != 0) {
179-
MaybeStackBuffer<Local<Value>, 16> args(2 + argc);
182+
if (use_async_hooks_trampoline) {
183+
MaybeStackBuffer<Local<Value>, 16> args(3 + argc);
180184
args[0] = v8::Number::New(env->isolate(), asyncContext.async_id);
181-
args[1] = callback;
185+
args[1] = resource;
186+
args[2] = callback;
182187
for (int i = 0; i < argc; i++) {
183-
args[i + 2] = argv[i];
188+
args[i + 3] = argv[i];
184189
}
185190
ret = hook_cb->Call(env->context(), recv, args.length(), &args[0]);
186191
} else {

src/async_wrap.cc

+21-2
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,7 @@ void AsyncWrap::PushAsyncContext(const FunctionCallbackInfo<Value>& args) {
502502
// then the checks in push_async_ids() and pop_async_id() will.
503503
double async_id = args[0]->NumberValue(env->context()).FromJust();
504504
double trigger_async_id = args[1]->NumberValue(env->context()).FromJust();
505-
env->async_hooks()->push_async_context(async_id, trigger_async_id, args[2]);
505+
env->async_hooks()->push_async_context(async_id, trigger_async_id, {});
506506
}
507507

508508

@@ -513,6 +513,22 @@ void AsyncWrap::PopAsyncContext(const FunctionCallbackInfo<Value>& args) {
513513
}
514514

515515

516+
void AsyncWrap::ExecutionAsyncResource(
517+
const FunctionCallbackInfo<Value>& args) {
518+
Environment* env = Environment::GetCurrent(args);
519+
uint32_t index;
520+
if (!args[0]->Uint32Value(env->context()).To(&index)) return;
521+
args.GetReturnValue().Set(
522+
env->async_hooks()->native_execution_async_resource(index));
523+
}
524+
525+
526+
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
527+
Environment* env = Environment::GetCurrent(args);
528+
env->async_hooks()->clear_async_id_stack();
529+
}
530+
531+
516532
void AsyncWrap::AsyncReset(const FunctionCallbackInfo<Value>& args) {
517533
CHECK(args[0]->IsObject());
518534

@@ -586,6 +602,8 @@ void AsyncWrap::Initialize(Local<Object> target,
586602
env->SetMethod(target, "setCallbackTrampoline", SetCallbackTrampoline);
587603
env->SetMethod(target, "pushAsyncContext", PushAsyncContext);
588604
env->SetMethod(target, "popAsyncContext", PopAsyncContext);
605+
env->SetMethod(target, "executionAsyncResource", ExecutionAsyncResource);
606+
env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack);
589607
env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId);
590608
env->SetMethod(target, "enablePromiseHook", EnablePromiseHook);
591609
env->SetMethod(target, "disablePromiseHook", DisablePromiseHook);
@@ -624,7 +642,7 @@ void AsyncWrap::Initialize(Local<Object> target,
624642

625643
FORCE_SET_TARGET_FIELD(target,
626644
"execution_async_resources",
627-
env->async_hooks()->execution_async_resources());
645+
env->async_hooks()->js_execution_async_resources());
628646

629647
target->Set(context,
630648
env->async_ids_stack_string(),
@@ -646,6 +664,7 @@ void AsyncWrap::Initialize(Local<Object> target,
646664
SET_HOOKS_CONSTANT(kTriggerAsyncId);
647665
SET_HOOKS_CONSTANT(kAsyncIdCounter);
648666
SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
667+
SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource);
649668
SET_HOOKS_CONSTANT(kStackLength);
650669
#undef SET_HOOKS_CONSTANT
651670
FORCE_SET_TARGET_FIELD(target, "constants", constants);

src/async_wrap.h

+4
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,10 @@ class AsyncWrap : public BaseObject {
137137
static void GetAsyncId(const v8::FunctionCallbackInfo<v8::Value>& args);
138138
static void PushAsyncContext(const v8::FunctionCallbackInfo<v8::Value>& args);
139139
static void PopAsyncContext(const v8::FunctionCallbackInfo<v8::Value>& args);
140+
static void ExecutionAsyncResource(
141+
const v8::FunctionCallbackInfo<v8::Value>& args);
142+
static void ClearAsyncIdStack(
143+
const v8::FunctionCallbackInfo<v8::Value>& args);
140144
static void AsyncReset(const v8::FunctionCallbackInfo<v8::Value>& args);
141145
static void GetProviderType(const v8::FunctionCallbackInfo<v8::Value>& args);
142146
static void QueueDestroyAsyncId(

src/env-inl.h

+59-13
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,17 @@ inline AliasedFloat64Array& AsyncHooks::async_ids_stack() {
105105
return async_ids_stack_;
106106
}
107107

108-
inline v8::Local<v8::Array> AsyncHooks::execution_async_resources() {
109-
return PersistentToLocal::Strong(execution_async_resources_);
108+
v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() {
109+
if (UNLIKELY(js_execution_async_resources_.IsEmpty())) {
110+
js_execution_async_resources_.Reset(
111+
env()->isolate(), v8::Array::New(env()->isolate()));
112+
}
113+
return PersistentToLocal::Strong(js_execution_async_resources_);
114+
}
115+
116+
v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) {
117+
if (i >= native_execution_async_resources_.size()) return {};
118+
return PersistentToLocal::Strong(native_execution_async_resources_[i]);
110119
}
111120

112121
inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) {
@@ -124,9 +133,7 @@ inline Environment* AsyncHooks::env() {
124133
// Remember to keep this code aligned with pushAsyncContext() in JS.
125134
inline void AsyncHooks::push_async_context(double async_id,
126135
double trigger_async_id,
127-
v8::Local<v8::Value> resource) {
128-
v8::HandleScope handle_scope(env()->isolate());
129-
136+
v8::Local<v8::Object> resource) {
130137
// Since async_hooks is experimental, do only perform the check
131138
// when async_hooks is enabled.
132139
if (fields_[kCheck] > 0) {
@@ -143,8 +150,19 @@ inline void AsyncHooks::push_async_context(double async_id,
143150
async_id_fields_[kExecutionAsyncId] = async_id;
144151
async_id_fields_[kTriggerAsyncId] = trigger_async_id;
145152

146-
auto resources = execution_async_resources();
147-
USE(resources->Set(env()->context(), offset, resource));
153+
#ifdef DEBUG
154+
for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
155+
CHECK(native_execution_async_resources_[i].IsEmpty());
156+
#endif
157+
158+
// When this call comes from JS (as a way of increasing the stack size),
159+
// `resource` will be empty, because JS caches these values anyway, and
160+
// we should avoid creating strong global references that might keep
161+
// these JS resource objects alive longer than necessary.
162+
if (!resource.IsEmpty()) {
163+
native_execution_async_resources_.resize(offset + 1);
164+
native_execution_async_resources_[offset].Reset(env()->isolate(), resource);
165+
}
148166
}
149167

150168
// Remember to keep this code aligned with popAsyncContext() in JS.
@@ -177,17 +195,45 @@ inline bool AsyncHooks::pop_async_context(double async_id) {
177195
async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
178196
fields_[kStackLength] = offset;
179197

180-
auto resources = execution_async_resources();
181-
USE(resources->Delete(env()->context(), offset));
198+
if (LIKELY(offset < native_execution_async_resources_.size() &&
199+
!native_execution_async_resources_[offset].IsEmpty())) {
200+
#ifdef DEBUG
201+
for (uint32_t i = offset + 1;
202+
i < native_execution_async_resources_.size();
203+
i++) {
204+
CHECK(native_execution_async_resources_[i].IsEmpty());
205+
}
206+
#endif
207+
native_execution_async_resources_.resize(offset);
208+
if (native_execution_async_resources_.size() <
209+
native_execution_async_resources_.capacity() / 2 &&
210+
native_execution_async_resources_.size() > 16) {
211+
native_execution_async_resources_.shrink_to_fit();
212+
}
213+
}
214+
215+
if (UNLIKELY(js_execution_async_resources()->Length() > offset)) {
216+
v8::HandleScope handle_scope(env()->isolate());
217+
USE(js_execution_async_resources()->Set(
218+
env()->context(),
219+
env()->length_string(),
220+
v8::Integer::NewFromUnsigned(env()->isolate(), offset)));
221+
}
182222

183223
return fields_[kStackLength] > 0;
184224
}
185225

186-
// Keep in sync with clearAsyncIdStack in lib/internal/async_hooks.js.
187-
inline void AsyncHooks::clear_async_id_stack() {
188-
auto isolate = env()->isolate();
226+
void AsyncHooks::clear_async_id_stack() {
227+
v8::Isolate* isolate = env()->isolate();
189228
v8::HandleScope handle_scope(isolate);
190-
execution_async_resources_.Reset(isolate, v8::Array::New(isolate));
229+
if (!js_execution_async_resources_.IsEmpty()) {
230+
USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set(
231+
env()->context(),
232+
env()->length_string(),
233+
v8::Integer::NewFromUnsigned(isolate, 0)));
234+
}
235+
native_execution_async_resources_.clear();
236+
native_execution_async_resources_.shrink_to_fit();
191237

192238
async_id_fields_[kExecutionAsyncId] = 0;
193239
async_id_fields_[kTriggerAsyncId] = 0;

src/env.h

+11-3
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ constexpr size_t kFsStatsBufferLength =
274274
V(issuercert_string, "issuerCertificate") \
275275
V(kill_signal_string, "killSignal") \
276276
V(kind_string, "kind") \
277+
V(length_string, "length") \
277278
V(library_string, "library") \
278279
V(mac_string, "mac") \
279280
V(max_buffer_string, "maxBuffer") \
@@ -618,6 +619,7 @@ class AsyncHooks : public MemoryRetainer {
618619
kTotals,
619620
kCheck,
620621
kStackLength,
622+
kUsesExecutionAsyncResource,
621623
kFieldsCount,
622624
};
623625

@@ -632,15 +634,20 @@ class AsyncHooks : public MemoryRetainer {
632634
inline AliasedUint32Array& fields();
633635
inline AliasedFloat64Array& async_id_fields();
634636
inline AliasedFloat64Array& async_ids_stack();
635-
inline v8::Local<v8::Array> execution_async_resources();
637+
inline v8::Local<v8::Array> js_execution_async_resources();
638+
// Returns the native executionAsyncResource value at stack index `index`.
639+
// Resources provided on the JS side are not stored on the native stack,
640+
// in which case an empty `Local<>` is returned.
641+
// The `js_execution_async_resources` array contains the value in that case.
642+
inline v8::Local<v8::Object> native_execution_async_resource(size_t index);
636643

637644
inline v8::Local<v8::String> provider_string(int idx);
638645

639646
inline void no_force_checks();
640647
inline Environment* env();
641648

642649
inline void push_async_context(double async_id, double trigger_async_id,
643-
v8::Local<v8::Value> execution_async_resource_);
650+
v8::Local<v8::Object> execution_async_resource_);
644651
inline bool pop_async_context(double async_id);
645652
inline void clear_async_id_stack(); // Used in fatal exceptions.
646653

@@ -685,7 +692,8 @@ class AsyncHooks : public MemoryRetainer {
685692

686693
void grow_async_ids_stack();
687694

688-
v8::Global<v8::Array> execution_async_resources_;
695+
v8::Global<v8::Array> js_execution_async_resources_;
696+
std::vector<v8::Global<v8::Object>> native_execution_async_resources_;
689697
};
690698

691699
class ImmediateInfo : public MemoryRetainer {

0 commit comments

Comments
 (0)