Skip to content

Commit 66b266e

Browse files
committed
fix(core): restart node with the required V8 flags
Launchers that start node by absolute path, such as Bazel's rules_js, never run the runner's node wrapper on PATH. tinybench and benchmark.js then measured without the flags getV8Flags() requires: --no-opt, --predictable, the seed flags, and the GC flags. ensureV8Flags() now replaces the process before any benchmark or instrument-hooks state exists, appending only the missing flags to the current execArgv and argv. The restart reuses the running executable: /proc/self/exe on Linux because rules_js replaces process.execPath with its shell shim, which would re-add --require. A native execv binding keeps the PID, environment and open descriptors, so cancellation and the runner FIFO are unaffected; it clears FD_CLOEXEC on stdio like process.execve, otherwise the restarted process writes to /dev/null. The PID marker stops a restart loop when the launcher strips the flags again, and worker threads, IPC children, unsupported platforms, and unbound addons keep the previous warning behavior. Instrument-hooks is now initialized on first use instead of at module load, because the restart discards the module state and must not leave a half-initialized instance behind. Closes COD-4038
1 parent 727b808 commit 66b266e

9 files changed

Lines changed: 310 additions & 24 deletions

File tree

‎packages/benchmark.js-plugin/src/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
ensureV8Flags,
23
getCallingFile,
34
InstrumentHooks,
45
mongoMeasurement,
@@ -19,6 +20,10 @@ import { CodSpeedBenchmark } from "./types";
1920
declare const __VERSION__: string;
2021

2122
tryIntrospect();
23+
// Before any benchmark or instrument-hooks state exists: the restart replaces
24+
// this process, and a launcher that runs node by absolute path (e.g. Bazel's
25+
// rules_js) never runs the runner's `node` wrapper.
26+
ensureV8Flags();
2227

2328
interface WithCodSpeedBenchmark extends Omit<
2429
Benchmark,

‎packages/core/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ export type {
5252
SetupInstrumentsRequestBody,
5353
SetupInstrumentsResponse,
5454
} from "./generated/openapi";
55-
export { getV8Flags, tryIntrospect } from "./introspection";
55+
export { ensureV8Flags, getV8Flags, tryIntrospect } from "./introspection";
5656
export {
5757
getUnsupportedNodeVersionWarning,
5858
SUPPORTED_NODE_MAJORS,

‎packages/core/src/introspection.ts‎

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
import { writeFileSync } from "fs";
1+
import { readlinkSync, writeFileSync } from "fs";
22
import path from "path";
3+
import { isMainThread } from "worker_threads";
34

4-
import { getInstrumentMode } from "./runnerMode";
5+
import native_core from "./native_core";
6+
import { getCodspeedRunnerMode, getInstrumentMode } from "./runnerMode";
57

68
const CUSTOM_INTROSPECTION_EXIT_CODE = 0;
79

810
const V8_LOG_FILENAME_PATTERN = "codspeed-v8-%p.log";
11+
const RESTARTED_PID_ENV = "__CODSPEED_NODE_CORE_RESTARTED_PID__";
912

1013
// Fixed seeds so Math.random() and hash table layout match on every run
1114
const getSeedFlags = (nodeVersionMajor: number) => {
@@ -91,6 +94,63 @@ export const tryIntrospect = () => {
9194
}
9295
};
9396

97+
/**
98+
* Restarts the process with the V8 flags the runner mode requires when the
99+
* launcher did not pass them (e.g. Bazel executes node by absolute path, so the
100+
* runner's `node` wrapper never runs). Must be called before instrument-hooks
101+
* is used: the restart replaces this process.
102+
*
103+
* Cases that cannot restart safely keep the previous behavior: `checkV8Flags`
104+
* warns once instrument-hooks is set up.
105+
*/
106+
export const ensureV8Flags = () => {
107+
if (getCodspeedRunnerMode() === "disabled" || !native_core.isBound) {
108+
return;
109+
}
110+
111+
const missingFlags = getV8Flags().filter(
112+
(flag) => !process.execArgv.includes(flag),
113+
);
114+
if (missingFlags.length === 0) {
115+
return;
116+
}
117+
118+
// Worker threads and IPC children cannot replace their process, and an IPC
119+
// channel would be lost.
120+
if (!isMainThread || process.send !== undefined) {
121+
return;
122+
}
123+
124+
// The restart did not help (its launcher stripped the flags again): do not
125+
// restart in a loop.
126+
if (process.env[RESTARTED_PID_ENV] === String(process.pid)) {
127+
return;
128+
}
129+
130+
const executable = (() => {
131+
switch (process.platform) {
132+
case "linux":
133+
// rules_js replaces process.execPath with its shell shim.
134+
return readlinkSync("/proc/self/exe");
135+
case "darwin":
136+
return process.execPath;
137+
default:
138+
return undefined;
139+
}
140+
})();
141+
if (executable === undefined) {
142+
return;
143+
}
144+
145+
process.env[RESTARTED_PID_ENV] = String(process.pid);
146+
native_core.restart(executable, [
147+
executable,
148+
...process.execArgv,
149+
...missingFlags,
150+
...process.argv.slice(1),
151+
]);
152+
};
153+
94154
export const checkV8Flags = () => {
95155
const requiredFlags = getV8Flags();
96156
const actualFlags = process.execArgv;

‎packages/core/src/native_core/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { LinuxPerf } from "./linux_perf/linux_perf";
55
interface NativeCore {
66
InstrumentHooks: InstrumentHooks;
77
LinuxPerf: typeof LinuxPerf;
8+
restart(executable: string, args: string[]): never;
89
}
910

1011
interface NativeCoreWithBindingStatus extends NativeCore {
@@ -26,6 +27,11 @@ try {
2627
logDebug("Failed to bind native core, instruments will not work.");
2728
logDebug(e);
2829
native_core = {
30+
restart: () => {
31+
throw new Error(
32+
`[CodSpeed] Cannot restart Node.js because the native core module is not bound: ${String(e)}`,
33+
);
34+
},
2935
LinuxPerf: class LinuxPerf {
3036
start() {
3137
return false;

‎packages/core/src/native_core/instruments/hooks_wrapper.cc‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,39 @@ namespace codspeed_native {
66
namespace instruments {
77
namespace hooks_wrapper {
88

9-
static InstrumentHooks *hooks = nullptr;
10-
11-
void InitializeGlobal() {
12-
if (!hooks) {
13-
hooks = instrument_hooks_init();
14-
}
9+
namespace {
10+
11+
// The single process-wide instrument-hooks instance, created on first use.
12+
//
13+
// A function-local static is initialized exactly once, thread-safely (C++11
14+
// magic statics), and never before a hook is actually used: creating the
15+
// instance opens the runner FIFO and writes environment data, so importing the
16+
// module must stay free of instrumentation side effects.
17+
InstrumentHooks *GetHooks() {
18+
static InstrumentHooks *hooks = instrument_hooks_init();
19+
return hooks;
1520
}
1621

22+
} // namespace
23+
1724
Napi::Boolean IsInstrumented(const Napi::CallbackInfo &info) {
1825
Napi::Env env = info.Env();
1926

20-
bool instrumented = instrument_hooks_is_instrumented(hooks);
27+
bool instrumented = instrument_hooks_is_instrumented(GetHooks());
2128
return Napi::Boolean::New(env, instrumented);
2229
}
2330

2431
Napi::Number StartBenchmark(const Napi::CallbackInfo &info) {
2532
Napi::Env env = info.Env();
2633

27-
uint8_t result = instrument_hooks_start_benchmark(hooks);
34+
uint8_t result = instrument_hooks_start_benchmark(GetHooks());
2835
return Napi::Number::New(env, result);
2936
}
3037

3138
Napi::Number StopBenchmark(const Napi::CallbackInfo &info) {
3239
Napi::Env env = info.Env();
3340

34-
uint8_t result = instrument_hooks_stop_benchmark(hooks);
41+
uint8_t result = instrument_hooks_stop_benchmark(GetHooks());
3542
return Napi::Number::New(env, result);
3643
}
3744

@@ -54,7 +61,7 @@ Napi::Number SetExecutedBenchmark(const Napi::CallbackInfo &info) {
5461
std::string uri = info[1].As<Napi::String>().Utf8Value();
5562

5663
uint8_t result =
57-
instrument_hooks_set_executed_benchmark(hooks, pid, uri.c_str());
64+
instrument_hooks_set_executed_benchmark(GetHooks(), pid, uri.c_str());
5865
return Napi::Number::New(env, result);
5966
}
6067

@@ -76,8 +83,8 @@ Napi::Number SetIntegration(const Napi::CallbackInfo &info) {
7683
std::string name = info[0].As<Napi::String>().Utf8Value();
7784
std::string version = info[1].As<Napi::String>().Utf8Value();
7885

79-
uint8_t result =
80-
instrument_hooks_set_integration(hooks, name.c_str(), version.c_str());
86+
uint8_t result = instrument_hooks_set_integration(
87+
GetHooks(), name.c_str(), version.c_str());
8188
return Napi::Number::New(env, result);
8289
}
8390

@@ -104,7 +111,7 @@ Napi::Number SetEnvironment(const Napi::CallbackInfo &info) {
104111
std::string value = info[2].As<Napi::String>().Utf8Value();
105112

106113
uint8_t result = instrument_hooks_set_environment(
107-
hooks, section_name.c_str(), key.c_str(), value.c_str());
114+
GetHooks(), section_name.c_str(), key.c_str(), value.c_str());
108115
return Napi::Number::New(env, result);
109116
}
110117

@@ -125,7 +132,7 @@ Napi::Number WriteEnvironment(const Napi::CallbackInfo &info) {
125132

126133
int32_t pid = info[0].As<Napi::Number>().Int32Value();
127134

128-
uint8_t result = instrument_hooks_write_environment(hooks, pid);
135+
uint8_t result = instrument_hooks_write_environment(GetHooks(), pid);
129136
return Napi::Number::New(env, result);
130137
}
131138

@@ -193,7 +200,7 @@ Napi::Number AddMarker(const Napi::CallbackInfo &info) {
193200
}
194201

195202
uint8_t result =
196-
instrument_hooks_add_marker(hooks, pid, marker_type, timestamp);
203+
instrument_hooks_add_marker(GetHooks(), pid, marker_type, timestamp);
197204
return Napi::Number::New(env, result);
198205
}
199206

@@ -221,8 +228,6 @@ Napi::Value __attribute__ ((noinline)) __codspeed_root_frame__(const Napi::Callb
221228
Napi::Object Initialize(Napi::Env env, Napi::Object exports) {
222229
Napi::Object instrumentHooksObj = Napi::Object::New(env);
223230

224-
InitializeGlobal();
225-
226231
instrumentHooksObj.Set(Napi::String::New(env, "isInstrumented"),
227232
Napi::Function::New(env, IsInstrumented));
228233
instrumentHooksObj.Set(Napi::String::New(env, "startBenchmark"),

‎packages/core/src/native_core/instruments/hooks_wrapper.h‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@ namespace codspeed_native {
77
namespace instruments {
88
namespace hooks_wrapper {
99

10-
// Global initialization
11-
// WARNING: InitializeGlobal() must be called before using any other functions
12-
// All API functions assume the global instance is already initialized
13-
void InitializeGlobal();
10+
// The process-wide instrument-hooks instance is created lazily, on first use,
11+
// so importing this module never initializes instrument-hooks as a side effect.
1412

1513
Napi::Boolean IsInstrumented(const Napi::CallbackInfo &info);
1614
Napi::Number StartBenchmark(const Napi::CallbackInfo &info);

‎packages/core/src/native_core/native_core.cc‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,148 @@
22
#include "instruments/hooks_wrapper.h"
33
#include <napi.h>
44

5+
#include <cerrno>
6+
#include <cstring>
7+
#include <string>
8+
#include <vector>
9+
10+
#if !defined(_WIN32)
11+
#include <fcntl.h>
12+
#include <unistd.h>
13+
#endif
14+
515
namespace codspeed_native {
616

17+
namespace {
18+
19+
bool ContainsNulByte(const std::string &value) {
20+
return value.find('\0') != std::string::npos;
21+
}
22+
23+
#if !defined(_WIN32)
24+
// `execv` keeps descriptors marked close-on-exec closed in the new image, and
25+
// libuv marks the stdio descriptors that way. Clear the flag like Node's own
26+
// `process.execve` does, otherwise the restarted process writes to /dev/null.
27+
int PersistStandardStream(int fd) {
28+
const int flags = fcntl(fd, F_GETFD, 0);
29+
if (flags < 0) {
30+
return flags;
31+
}
32+
return fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC);
33+
}
34+
#endif
35+
36+
// Replaces the current process image with `executable` using POSIX `execv`.
37+
//
38+
// Replacing the image in place (instead of spawning a child) keeps the PID,
39+
// the working directory, the environment and the open file descriptors --
40+
// notably the runner FIFO used by instrument-hooks -- intact. On success this
41+
// function never returns; on failure it throws and the current image stays
42+
// usable.
43+
Napi::Value Restart(const Napi::CallbackInfo &info) {
44+
Napi::Env env = info.Env();
45+
46+
if (info.Length() != 2) {
47+
Napi::TypeError::New(env, "Expected 2 arguments: executable and args")
48+
.ThrowAsJavaScriptException();
49+
return env.Undefined();
50+
}
51+
52+
if (!info[0].IsString()) {
53+
Napi::TypeError::New(env, "Expected string (executable)")
54+
.ThrowAsJavaScriptException();
55+
return env.Undefined();
56+
}
57+
58+
if (!info[1].IsArray()) {
59+
Napi::TypeError::New(env, "Expected array of strings (args)")
60+
.ThrowAsJavaScriptException();
61+
return env.Undefined();
62+
}
63+
64+
const std::string executable = info[0].As<Napi::String>().Utf8Value();
65+
if (executable.empty()) {
66+
Napi::TypeError::New(env, "Expected non-empty string (executable)")
67+
.ThrowAsJavaScriptException();
68+
return env.Undefined();
69+
}
70+
if (ContainsNulByte(executable)) {
71+
Napi::TypeError::New(env, "executable must not contain NUL bytes")
72+
.ThrowAsJavaScriptException();
73+
return env.Undefined();
74+
}
75+
76+
const Napi::Array args = info[1].As<Napi::Array>();
77+
const uint32_t argc = args.Length();
78+
if (argc == 0) {
79+
Napi::TypeError::New(env, "Expected at least argv[0] in args: pass the "
80+
"complete argv, including the program name")
81+
.ThrowAsJavaScriptException();
82+
return env.Undefined();
83+
}
84+
85+
// Fill the strings before taking any pointer out of them: `execv` needs
86+
// stable storage, so the vector must not reallocate afterwards.
87+
std::vector<std::string> arg_strings;
88+
arg_strings.reserve(argc);
89+
for (uint32_t i = 0; i < argc; i++) {
90+
const Napi::Value arg = args.Get(i);
91+
if (!arg.IsString()) {
92+
Napi::TypeError::New(env, "Expected string (args[" + std::to_string(i) +
93+
"])")
94+
.ThrowAsJavaScriptException();
95+
return env.Undefined();
96+
}
97+
arg_strings.push_back(arg.As<Napi::String>().Utf8Value());
98+
if (ContainsNulByte(arg_strings.back())) {
99+
Napi::TypeError::New(env, "args[" + std::to_string(i) +
100+
"] must not contain NUL bytes")
101+
.ThrowAsJavaScriptException();
102+
return env.Undefined();
103+
}
104+
}
105+
106+
#if defined(_WIN32)
107+
Napi::Error::New(env, "restart() is not supported on Windows: pass the "
108+
"required Node.js flags from the launcher")
109+
.ThrowAsJavaScriptException();
110+
return env.Undefined();
111+
#else
112+
std::vector<char *> argv;
113+
argv.reserve(arg_strings.size() + 1);
114+
for (std::string &arg : arg_strings) {
115+
argv.push_back(const_cast<char *>(arg.c_str()));
116+
}
117+
argv.push_back(nullptr);
118+
119+
if (PersistStandardStream(0) < 0 || PersistStandardStream(1) < 0 ||
120+
PersistStandardStream(2) < 0) {
121+
const int fcntl_errno = errno;
122+
Napi::Error::New(env, "Failed to keep stdio open across restart: " +
123+
std::string(std::strerror(fcntl_errno)))
124+
.ThrowAsJavaScriptException();
125+
return env.Undefined();
126+
}
127+
128+
execv(executable.c_str(), argv.data());
129+
130+
// Reaching this point means the exec failed and the current process is still
131+
// running. Capture errno before any further N-API call can clobber it.
132+
const int exec_errno = errno;
133+
Napi::Error::New(env, "Failed to restart with execv(\"" + executable +
134+
"\"): " + std::strerror(exec_errno))
135+
.ThrowAsJavaScriptException();
136+
return env.Undefined();
137+
#endif
138+
}
139+
140+
} // namespace
141+
7142
Napi::Object Initialize(Napi::Env env, Napi::Object exports) {
8143
codspeed_native::LinuxPerf::Initialize(env, exports);
9144
codspeed_native::instruments::hooks_wrapper::Initialize(env, exports);
145+
exports.Set(Napi::String::New(env, "restart"),
146+
Napi::Function::New(env, Restart));
10147

11148
return exports;
12149
}

0 commit comments

Comments
 (0)