Skip to content

Commit dd56bd1

Browse files
addaleaxevanlucas
authored andcommitted
async_hooks: use typed array stack as fast path
- Communicate the current async stack length through a typed array field rather than a native binding method - Add a new fixed-size `async_ids_fast_stack` typed array that contains the async ID stack up to a fixed limit. This increases performance noticeably, since most of the time the async ID stack will not be more than a handful of levels deep. - Make the JS `pushAsyncIds()` and `popAsyncIds()` functions do the same thing as the native ones if the fast path is applicable. Benchmarks: $ ./node benchmark/compare.js --new ./node --old ./node-master --runs 10 --filter next-tick process | Rscript benchmark/compare.R [00:03:25|% 100| 6/6 files | 20/20 runs | 1/1 configs]: Done improvement confidence p.value process/next-tick-breadth-args.js millions=4 19.72 % *** 3.013913e-06 process/next-tick-breadth.js millions=4 27.33 % *** 5.847983e-11 process/next-tick-depth-args.js millions=12 40.08 % *** 1.237127e-13 process/next-tick-depth.js millions=12 77.27 % *** 1.413290e-11 process/next-tick-exec-args.js millions=5 13.58 % *** 1.245180e-07 process/next-tick-exec.js millions=5 16.80 % *** 2.961386e-07 Backport-PR-URL: #18290 PR-URL: #17780 Reviewed-By: James M Snell <[email protected]>
1 parent 722fe46 commit dd56bd1

9 files changed

+164
-54
lines changed

lib/internal/async_hooks.js

+41-3
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,20 @@ const async_wrap = process.binding('async_wrap');
1919
* retrieving the triggerAsyncId value is passing directly to the
2020
* constructor -> value set in kDefaultTriggerAsyncId -> executionAsyncId of
2121
* the current resource.
22+
*
23+
* async_ids_fast_stack is a Float64Array that contains part of the async ID
24+
* stack. Each pushAsyncIds() call adds two doubles to it, and each
25+
* popAsyncIds() call removes two doubles from it.
26+
* It has a fixed size, so if that is exceeded, calls to the native
27+
* side are used instead in pushAsyncIds() and popAsyncIds().
2228
*/
2329
const { async_hook_fields, async_id_fields } = async_wrap;
2430
// Store the pair executionAsyncId and triggerAsyncId in a std::stack on
2531
// Environment::AsyncHooks::ids_stack_ tracks the resource responsible for the
2632
// current execution stack. This is unwound as each resource exits. In the case
2733
// of a fatal exception this stack is emptied after calling each hook's after()
2834
// callback.
29-
const { pushAsyncIds, popAsyncIds } = async_wrap;
35+
const { pushAsyncIds: pushAsyncIds_, popAsyncIds: popAsyncIds_ } = async_wrap;
3036
// For performance reasons, only track Proimses when a hook is enabled.
3137
const { enablePromiseHook, disablePromiseHook } = async_wrap;
3238
// Properties in active_hooks are used to keep track of the set of hooks being
@@ -60,8 +66,8 @@ const active_hooks = {
6066
// async execution. These are tracked so if the user didn't include callbacks
6167
// for a given step, that step can bail out early.
6268
const { kInit, kBefore, kAfter, kDestroy, kPromiseResolve,
63-
kCheck, kExecutionAsyncId, kAsyncIdCounter,
64-
kDefaultTriggerAsyncId } = async_wrap.constants;
69+
kCheck, kExecutionAsyncId, kAsyncIdCounter, kTriggerAsyncId,
70+
kDefaultTriggerAsyncId, kStackLength } = async_wrap.constants;
6571

6672
// Used in AsyncHook and AsyncResource.
6773
const init_symbol = Symbol('init');
@@ -329,6 +335,38 @@ function emitDestroyScript(asyncId) {
329335
}
330336

331337

338+
// This is the equivalent of the native push_async_ids() call.
339+
function pushAsyncIds(asyncId, triggerAsyncId) {
340+
const offset = async_hook_fields[kStackLength];
341+
if (offset * 2 >= async_wrap.async_ids_stack.length)
342+
return pushAsyncIds_(asyncId, triggerAsyncId);
343+
async_wrap.async_ids_stack[offset * 2] = async_id_fields[kExecutionAsyncId];
344+
async_wrap.async_ids_stack[offset * 2 + 1] = async_id_fields[kTriggerAsyncId];
345+
async_hook_fields[kStackLength]++;
346+
async_id_fields[kExecutionAsyncId] = asyncId;
347+
async_id_fields[kTriggerAsyncId] = triggerAsyncId;
348+
}
349+
350+
351+
// This is the equivalent of the native pop_async_ids() call.
352+
function popAsyncIds(asyncId) {
353+
if (async_hook_fields[kStackLength] === 0) return false;
354+
const stackLength = async_hook_fields[kStackLength];
355+
356+
if (async_hook_fields[kCheck] > 0 &&
357+
async_id_fields[kExecutionAsyncId] !== asyncId) {
358+
// Do the same thing as the native code (i.e. crash hard).
359+
return popAsyncIds_(asyncId);
360+
}
361+
362+
const offset = stackLength - 1;
363+
async_id_fields[kExecutionAsyncId] = async_wrap.async_ids_stack[2 * offset];
364+
async_id_fields[kTriggerAsyncId] = async_wrap.async_ids_stack[2 * offset + 1];
365+
async_hook_fields[kStackLength] = offset;
366+
return offset > 0;
367+
}
368+
369+
332370
module.exports = {
333371
// Private API
334372
getHookArrays,

lib/internal/bootstrap_node.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -366,9 +366,9 @@
366366
// Arrays containing hook flags and ids for async_hook calls.
367367
const { async_hook_fields, async_id_fields } = async_wrap;
368368
// Internal functions needed to manipulate the stack.
369-
const { clearAsyncIdStack, asyncIdStackSize } = async_wrap;
369+
const { clearAsyncIdStack } = async_wrap;
370370
const { kAfter, kExecutionAsyncId,
371-
kDefaultTriggerAsyncId } = async_wrap.constants;
371+
kDefaultTriggerAsyncId, kStackLength } = async_wrap.constants;
372372

373373
process._fatalException = function(er) {
374374
var caught;
@@ -406,7 +406,7 @@
406406
do {
407407
NativeModule.require('internal/async_hooks').emitAfter(
408408
async_id_fields[kExecutionAsyncId]);
409-
} while (asyncIdStackSize() > 0);
409+
} while (async_hook_fields[kStackLength] > 0);
410410
// Or completely empty the id stack.
411411
} else {
412412
clearAsyncIdStack();

src/aliased_buffer.h

+27-2
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,21 @@ class AliasedBuffer {
9595
js_array_.Reset();
9696
}
9797

98+
AliasedBuffer& operator=(AliasedBuffer&& that) {
99+
this->~AliasedBuffer();
100+
isolate_ = that.isolate_;
101+
count_ = that.count_;
102+
byte_offset_ = that.byte_offset_;
103+
buffer_ = that.buffer_;
104+
free_buffer_ = that.free_buffer_;
105+
106+
js_array_.Reset(isolate_, that.js_array_.Get(isolate_));
107+
108+
that.buffer_ = nullptr;
109+
that.js_array_.Reset();
110+
return *this;
111+
}
112+
98113
/**
99114
* Helper class that is returned from operator[] to support assignment into
100115
* a specified location.
@@ -111,11 +126,17 @@ class AliasedBuffer {
111126
index_(that.index_) {
112127
}
113128

114-
inline Reference& operator=(const NativeT &val) {
129+
template <typename T>
130+
inline Reference& operator=(const T& val) {
115131
aliased_buffer_->SetValue(index_, val);
116132
return *this;
117133
}
118134

135+
// This is not caught by the template operator= above.
136+
inline Reference& operator=(const Reference& val) {
137+
return *this = static_cast<NativeT>(val);
138+
}
139+
119140
operator NativeT() const {
120141
return aliased_buffer_->GetValue(index_);
121142
}
@@ -186,8 +207,12 @@ class AliasedBuffer {
186207
return GetValue(index);
187208
}
188209

210+
size_t Length() const {
211+
return count_;
212+
}
213+
189214
private:
190-
v8::Isolate* const isolate_;
215+
v8::Isolate* isolate_;
191216
size_t count_;
192217
size_t byte_offset_;
193218
NativeT* buffer_;

src/async_wrap.cc

+6-8
Original file line numberDiff line numberDiff line change
@@ -467,13 +467,6 @@ void AsyncWrap::PopAsyncIds(const FunctionCallbackInfo<Value>& args) {
467467
}
468468

469469

470-
void AsyncWrap::AsyncIdStackSize(const FunctionCallbackInfo<Value>& args) {
471-
Environment* env = Environment::GetCurrent(args);
472-
args.GetReturnValue().Set(
473-
static_cast<double>(env->async_hooks()->stack_size()));
474-
}
475-
476-
477470
void AsyncWrap::ClearAsyncIdStack(const FunctionCallbackInfo<Value>& args) {
478471
Environment* env = Environment::GetCurrent(args);
479472
env->async_hooks()->clear_async_id_stack();
@@ -512,7 +505,6 @@ void AsyncWrap::Initialize(Local<Object> target,
512505
env->SetMethod(target, "setupHooks", SetupHooks);
513506
env->SetMethod(target, "pushAsyncIds", PushAsyncIds);
514507
env->SetMethod(target, "popAsyncIds", PopAsyncIds);
515-
env->SetMethod(target, "asyncIdStackSize", AsyncIdStackSize);
516508
env->SetMethod(target, "clearAsyncIdStack", ClearAsyncIdStack);
517509
env->SetMethod(target, "queueDestroyAsyncId", QueueDestroyAsyncId);
518510
env->SetMethod(target, "enablePromiseHook", EnablePromiseHook);
@@ -550,6 +542,10 @@ void AsyncWrap::Initialize(Local<Object> target,
550542
"async_id_fields",
551543
env->async_hooks()->async_id_fields().GetJSArray());
552544

545+
target->Set(context,
546+
env->async_ids_stack_string(),
547+
env->async_hooks()->async_ids_stack().GetJSArray()).FromJust();
548+
553549
Local<Object> constants = Object::New(isolate);
554550
#define SET_HOOKS_CONSTANT(name) \
555551
FORCE_SET_TARGET_FIELD( \
@@ -566,6 +562,7 @@ void AsyncWrap::Initialize(Local<Object> target,
566562
SET_HOOKS_CONSTANT(kTriggerAsyncId);
567563
SET_HOOKS_CONSTANT(kAsyncIdCounter);
568564
SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId);
565+
SET_HOOKS_CONSTANT(kStackLength);
569566
#undef SET_HOOKS_CONSTANT
570567
FORCE_SET_TARGET_FIELD(target, "constants", constants);
571568

@@ -595,6 +592,7 @@ void AsyncWrap::Initialize(Local<Object> target,
595592
env->set_async_hooks_after_function(Local<Function>());
596593
env->set_async_hooks_destroy_function(Local<Function>());
597594
env->set_async_hooks_promise_resolve_function(Local<Function>());
595+
env->set_async_hooks_binding(target);
598596
}
599597

600598

src/async_wrap.h

-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,6 @@ class AsyncWrap : public BaseObject {
123123
static void GetAsyncId(const v8::FunctionCallbackInfo<v8::Value>& args);
124124
static void PushAsyncIds(const v8::FunctionCallbackInfo<v8::Value>& args);
125125
static void PopAsyncIds(const v8::FunctionCallbackInfo<v8::Value>& args);
126-
static void AsyncIdStackSize(const v8::FunctionCallbackInfo<v8::Value>& args);
127126
static void ClearAsyncIdStack(
128127
const v8::FunctionCallbackInfo<v8::Value>& args);
129128
static void AsyncReset(const v8::FunctionCallbackInfo<v8::Value>& args);

src/env-inl.h

+38-24
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,11 @@ inline MultiIsolatePlatform* IsolateData::platform() const {
5353
return platform_;
5454
}
5555

56-
inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate)
57-
: isolate_(isolate),
58-
fields_(isolate, kFieldsCount),
59-
async_id_fields_(isolate, kUidFieldsCount) {
60-
v8::HandleScope handle_scope(isolate_);
56+
inline Environment::AsyncHooks::AsyncHooks()
57+
: async_ids_stack_(env()->isolate(), 16 * 2),
58+
fields_(env()->isolate(), kFieldsCount),
59+
async_id_fields_(env()->isolate(), kUidFieldsCount) {
60+
v8::HandleScope handle_scope(env()->isolate());
6161

6262
// Always perform async_hooks checks, not just when async_hooks is enabled.
6363
// TODO(AndreasMadsen): Consider removing this for LTS releases.
@@ -81,9 +81,9 @@ inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate)
8181
// strings can be retrieved quickly.
8282
#define V(Provider) \
8383
providers_[AsyncWrap::PROVIDER_ ## Provider].Set( \
84-
isolate_, \
84+
env()->isolate(), \
8585
v8::String::NewFromOneByte( \
86-
isolate_, \
86+
env()->isolate(), \
8787
reinterpret_cast<const uint8_t*>(#Provider), \
8888
v8::NewStringType::kInternalized, \
8989
sizeof(#Provider) - 1).ToLocalChecked());
@@ -101,15 +101,25 @@ Environment::AsyncHooks::async_id_fields() {
101101
return async_id_fields_;
102102
}
103103

104+
inline AliasedBuffer<double, v8::Float64Array>&
105+
Environment::AsyncHooks::async_ids_stack() {
106+
return async_ids_stack_;
107+
}
108+
104109
inline v8::Local<v8::String> Environment::AsyncHooks::provider_string(int idx) {
105-
return providers_[idx].Get(isolate_);
110+
return providers_[idx].Get(env()->isolate());
106111
}
107112

108113
inline void Environment::AsyncHooks::no_force_checks() {
109114
// fields_ does not have the -= operator defined
110115
fields_[kCheck] = fields_[kCheck] - 1;
111116
}
112117

118+
inline Environment* Environment::AsyncHooks::env() {
119+
return Environment::ForAsyncHooks(this);
120+
}
121+
122+
// Remember to keep this code aligned with pushAsyncIds() in JS.
113123
inline void Environment::AsyncHooks::push_async_ids(double async_id,
114124
double trigger_async_id) {
115125
// Since async_hooks is experimental, do only perform the check
@@ -119,16 +129,21 @@ inline void Environment::AsyncHooks::push_async_ids(double async_id,
119129
CHECK_GE(trigger_async_id, -1);
120130
}
121131

122-
async_ids_stack_.push({ async_id_fields_[kExecutionAsyncId],
123-
async_id_fields_[kTriggerAsyncId] });
132+
uint32_t offset = fields_[kStackLength];
133+
if (offset * 2 >= async_ids_stack_.Length())
134+
grow_async_ids_stack();
135+
async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId];
136+
async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId];
137+
fields_[kStackLength] = fields_[kStackLength] + 1;
124138
async_id_fields_[kExecutionAsyncId] = async_id;
125139
async_id_fields_[kTriggerAsyncId] = trigger_async_id;
126140
}
127141

142+
// Remember to keep this code aligned with popAsyncIds() in JS.
128143
inline bool Environment::AsyncHooks::pop_async_id(double async_id) {
129144
// In case of an exception then this may have already been reset, if the
130145
// stack was multiple MakeCallback()'s deep.
131-
if (async_ids_stack_.empty()) return false;
146+
if (fields_[kStackLength] == 0) return false;
132147

133148
// Ask for the async_id to be restored as a check that the stack
134149
// hasn't been corrupted.
@@ -140,32 +155,27 @@ inline bool Environment::AsyncHooks::pop_async_id(double async_id) {
140155
"actual: %.f, expected: %.f)\n",
141156
async_id_fields_.GetValue(kExecutionAsyncId),
142157
async_id);
143-
Environment* env = Environment::GetCurrent(isolate_);
144158
DumpBacktrace(stderr);
145159
fflush(stderr);
146-
if (!env->abort_on_uncaught_exception())
160+
if (!env()->abort_on_uncaught_exception())
147161
exit(1);
148162
fprintf(stderr, "\n");
149163
fflush(stderr);
150164
ABORT_NO_BACKTRACE();
151165
}
152166

153-
auto async_ids = async_ids_stack_.top();
154-
async_ids_stack_.pop();
155-
async_id_fields_[kExecutionAsyncId] = async_ids.async_id;
156-
async_id_fields_[kTriggerAsyncId] = async_ids.trigger_async_id;
157-
return !async_ids_stack_.empty();
158-
}
167+
uint32_t offset = fields_[kStackLength] - 1;
168+
async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
169+
async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
170+
fields_[kStackLength] = offset;
159171

160-
inline size_t Environment::AsyncHooks::stack_size() {
161-
return async_ids_stack_.size();
172+
return fields_[kStackLength] > 0;
162173
}
163174

164175
inline void Environment::AsyncHooks::clear_async_id_stack() {
165-
while (!async_ids_stack_.empty())
166-
async_ids_stack_.pop();
167176
async_id_fields_[kExecutionAsyncId] = 0;
168177
async_id_fields_[kTriggerAsyncId] = 0;
178+
fields_[kStackLength] = 0;
169179
}
170180

171181
inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
@@ -189,6 +199,11 @@ inline Environment::AsyncHooks::DefaultTriggerAsyncIdScope
189199
}
190200

191201

202+
Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) {
203+
return ContainerOf(&Environment::async_hooks_, hooks);
204+
}
205+
206+
192207
inline Environment::AsyncCallbackScope::AsyncCallbackScope(Environment* env)
193208
: env_(env) {
194209
env_->makecallback_cntr_++;
@@ -262,7 +277,6 @@ inline Environment::Environment(IsolateData* isolate_data,
262277
v8::Local<v8::Context> context)
263278
: isolate_(context->GetIsolate()),
264279
isolate_data_(isolate_data),
265-
async_hooks_(context->GetIsolate()),
266280
timer_base_(uv_now(isolate_data->event_loop())),
267281
using_domains_(false),
268282
printed_error_(false),

src/env.cc

+16
Original file line numberDiff line numberDiff line change
@@ -323,4 +323,20 @@ void Environment::ActivateImmediateCheck() {
323323
uv_idle_start(&immediate_idle_handle_, [](uv_idle_t*){ });
324324
}
325325

326+
void Environment::AsyncHooks::grow_async_ids_stack() {
327+
const uint32_t old_capacity = async_ids_stack_.Length() / 2;
328+
const uint32_t new_capacity = old_capacity * 1.5;
329+
AliasedBuffer<double, v8::Float64Array> new_buffer(
330+
env()->isolate(), new_capacity * 2);
331+
332+
for (uint32_t i = 0; i < old_capacity * 2; ++i)
333+
new_buffer[i] = async_ids_stack_[i];
334+
async_ids_stack_ = std::move(new_buffer);
335+
336+
env()->async_hooks_binding()->Set(
337+
env()->context(),
338+
env()->async_ids_stack_string(),
339+
async_ids_stack_.GetJSArray()).FromJust();
340+
}
341+
326342
} // namespace node

0 commit comments

Comments
 (0)