Skip to content

Commit c86f5b1

Browse files
committed
feat(core): add per-benchmark process isolation
Benchmarks of one binary share a process, so the allocator state and threads one benchmark leaves behind (raised mmap threshold, fragmented bins, retained caches) change the measurement of every benchmark after it. Adding or changing one benchmark can then shift unrelated results. Add `codspeed::Isolation`. It is on by default and turned off with `CODSPEED_PROCESS_ISOLATION=false` (or `0`); any other value than true/1/false/0 is an error. `Isolation::run` starts the benchmark executable again with the original arguments and `CODSPEED_ISOLATED_BENCHMARK` set to one benchmark URI, so each benchmark gets a fresh process. A failing child's exit code is propagated (128 + N for signal N). Re-exec instead of fork(): fork only copies the calling thread, so threads the binary started before the harness would be missing in the child and work sent to them would hang. Linux uses /proc/self/exe, macOS _NSGetExecutablePath; Windows is not supported.
1 parent 76985b6 commit c86f5b1

3 files changed

Lines changed: 273 additions & 0 deletions

File tree

‎core/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ endif()
8585
add_library(
8686
codspeed
8787
src/codspeed.cpp
88+
src/isolation.cpp
8889
src/measurement.cpp
8990
src/walltime.cpp
9091
src/uri.cpp

‎core/include/isolation.h‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#ifndef CODSPEED_ISOLATION_H
2+
#define CODSPEED_ISOLATION_H
3+
4+
#include <functional>
5+
#include <string>
6+
7+
namespace codspeed {
8+
9+
// Isolation is on unless this is `0` or `false`.
10+
extern const char* const PROCESS_ISOLATION_ENV;
11+
// Set on each child process: the URI of the only benchmark it runs.
12+
extern const char* const ISOLATED_BENCHMARK_ENV;
13+
14+
// How the harness runs each benchmark. Every benchmark runs in a fresh copy of
15+
// the benchmark executable by default, so the allocator state and threads that
16+
// other benchmarks or setup code leave behind can't change its measurement.
17+
class Isolation {
18+
public:
19+
enum class Kind {
20+
// All benchmarks share this process and its allocator state.
21+
SharedProcess,
22+
// Every benchmark runs in its own child process.
23+
ProcessPerBenchmark,
24+
// A child spawned by `ProcessPerBenchmark`, restricted to one URI.
25+
IsolatedBenchmark,
26+
};
27+
28+
// Stores the original command line. Call it before the arguments get
29+
// parsed, because parsing removes the flags it consumed. The child process
30+
// is started with the same arguments.
31+
static void set_argv(int argc, const char* const* argv);
32+
33+
// The isolation of this process, read once from the environment.
34+
static const Isolation& current();
35+
36+
Kind kind() const { return kind_; }
37+
38+
// The only benchmark this process may run, or null. It overrides CLI
39+
// filters.
40+
const std::string* only_benchmark() const;
41+
42+
// Runs the benchmark `uri`. `bench` must contain the whole measurement,
43+
// from `start_benchmark` to `end_benchmark`.
44+
void run(const std::string& uri, const std::function<void()>& bench) const;
45+
46+
// Runs this executable again with the same arguments, limited to `uri`, and
47+
// exits with the child's code if it fails.
48+
static void run_in_child_process(const std::string& uri);
49+
50+
private:
51+
Isolation(Kind kind, std::string isolated_uri);
52+
static Isolation from_env();
53+
54+
Kind kind_;
55+
std::string isolated_uri_;
56+
};
57+
58+
} // namespace codspeed
59+
60+
#endif // CODSPEED_ISOLATION_H

‎core/src/isolation.cpp‎

Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
#include "isolation.h"
2+
3+
#include <cstdio>
4+
#include <cstdlib>
5+
#include <cstring>
6+
#include <iostream>
7+
#include <string>
8+
#include <vector>
9+
10+
#include "utils.h"
11+
12+
#ifndef _WIN32
13+
#include <spawn.h>
14+
#include <sys/wait.h>
15+
#include <unistd.h>
16+
17+
#include <cerrno>
18+
#ifdef __APPLE__
19+
#include <mach-o/dyld.h>
20+
#endif
21+
22+
extern char** environ;
23+
#endif
24+
25+
namespace codspeed {
26+
27+
const char* const PROCESS_ISOLATION_ENV = "CODSPEED_PROCESS_ISOLATION";
28+
const char* const ISOLATED_BENCHMARK_ENV = "CODSPEED_ISOLATED_BENCHMARK";
29+
30+
namespace {
31+
32+
// Exit code for a child that ended with neither an exit code nor a signal.
33+
constexpr int GENERIC_FAILURE_EXIT_CODE = 1;
34+
// Shells report a child killed by signal N as exit code 128 + N.
35+
constexpr int SIGNAL_EXIT_CODE_OFFSET = 128;
36+
37+
#ifndef _WIN32
38+
// Path of the running executable. `/proc/self/exe` keeps working when the
39+
// benchmark changed its working directory or `argv[0]` is a bare name.
40+
std::string current_executable() {
41+
#if defined(__linux__)
42+
return "/proc/self/exe";
43+
#elif defined(__APPLE__)
44+
uint32_t size = 0;
45+
_NSGetExecutablePath(nullptr, &size);
46+
std::vector<char> buffer(size);
47+
if (_NSGetExecutablePath(buffer.data(), &size) == 0) {
48+
return std::string(buffer.data());
49+
}
50+
return std::string();
51+
#else
52+
return std::string();
53+
#endif
54+
}
55+
56+
// The environment of this process plus the isolated benchmark URI.
57+
std::vector<std::string> child_environment(const std::string& uri) {
58+
std::vector<std::string> env;
59+
const std::string isolated_prefix = std::string(ISOLATED_BENCHMARK_ENV) + "=";
60+
for (char** entry = environ; entry != nullptr && *entry != nullptr; ++entry) {
61+
if (std::strncmp(*entry, isolated_prefix.c_str(), isolated_prefix.size()) ==
62+
0) {
63+
continue;
64+
}
65+
env.emplace_back(*entry);
66+
}
67+
env.push_back(isolated_prefix + uri);
68+
return env;
69+
}
70+
71+
// Exit code of a failed child, in the shell convention.
72+
int exit_code(int wait_status) {
73+
if (WIFSIGNALED(wait_status)) {
74+
return SIGNAL_EXIT_CODE_OFFSET + WTERMSIG(wait_status);
75+
}
76+
if (WIFEXITED(wait_status)) {
77+
return WEXITSTATUS(wait_status);
78+
}
79+
return GENERIC_FAILURE_EXIT_CODE;
80+
}
81+
#endif
82+
83+
std::vector<std::string>& original_argv() {
84+
static std::vector<std::string> argv;
85+
return argv;
86+
}
87+
88+
} // namespace
89+
90+
void Isolation::set_argv(int argc, const char* const* argv) {
91+
auto& stored = original_argv();
92+
stored.clear();
93+
for (int i = 0; i < argc; ++i) {
94+
stored.emplace_back(argv[i]);
95+
}
96+
}
97+
98+
Isolation::Isolation(Kind kind, std::string isolated_uri)
99+
: kind_(kind), isolated_uri_(std::move(isolated_uri)) {}
100+
101+
const Isolation& Isolation::current() {
102+
static const Isolation instance = from_env();
103+
return instance;
104+
}
105+
106+
Isolation Isolation::from_env() {
107+
const std::string uri = safe_getenv(ISOLATED_BENCHMARK_ENV);
108+
if (!uri.empty()) {
109+
return Isolation(Kind::IsolatedBenchmark, uri);
110+
}
111+
112+
const std::string value = safe_getenv(PROCESS_ISOLATION_ENV);
113+
if (value.empty() || value == "1" || value == "true") {
114+
return Isolation(Kind::ProcessPerBenchmark, "");
115+
}
116+
if (value == "0" || value == "false") {
117+
return Isolation(Kind::SharedProcess, "");
118+
}
119+
120+
std::cerr << PROCESS_ISOLATION_ENV << " must be `true` or `false`, got `"
121+
<< value << "`" << std::endl;
122+
std::exit(GENERIC_FAILURE_EXIT_CODE);
123+
}
124+
125+
const std::string* Isolation::only_benchmark() const {
126+
return kind_ == Kind::IsolatedBenchmark ? &isolated_uri_ : nullptr;
127+
}
128+
129+
void Isolation::run(const std::string& uri,
130+
const std::function<void()>& bench) const {
131+
switch (kind_) {
132+
case Kind::SharedProcess:
133+
case Kind::IsolatedBenchmark:
134+
bench();
135+
return;
136+
case Kind::ProcessPerBenchmark:
137+
run_in_child_process(uri);
138+
return;
139+
}
140+
}
141+
142+
#ifdef _WIN32
143+
void Isolation::run_in_child_process(const std::string& uri) {
144+
std::cerr << "process isolation is not supported on Windows, set "
145+
<< PROCESS_ISOLATION_ENV << "=false (benchmark: " << uri << ")"
146+
<< std::endl;
147+
std::exit(GENERIC_FAILURE_EXIT_CODE);
148+
}
149+
#else
150+
void Isolation::run_in_child_process(const std::string& uri) {
151+
// Keep the parent's output before the child's.
152+
std::fflush(stdout);
153+
std::cout.flush();
154+
std::cerr.flush();
155+
156+
const std::string exe = current_executable();
157+
const auto& args = original_argv();
158+
if (exe.empty() && args.empty()) {
159+
std::cerr << "failed to locate the benchmark executable for " << uri
160+
<< std::endl;
161+
std::exit(GENERIC_FAILURE_EXIT_CODE);
162+
}
163+
164+
// Fall back to argv[0] where the OS gives no executable path.
165+
const std::string& program = exe.empty() ? args[0] : exe;
166+
167+
std::vector<std::string> argv_storage = args;
168+
if (argv_storage.empty()) {
169+
argv_storage.push_back(program);
170+
}
171+
std::vector<char*> argv;
172+
for (auto& arg : argv_storage) {
173+
argv.push_back(&arg[0]);
174+
}
175+
argv.push_back(nullptr);
176+
177+
std::vector<std::string> env_storage = child_environment(uri);
178+
std::vector<char*> envp;
179+
for (auto& entry : env_storage) {
180+
envp.push_back(&entry[0]);
181+
}
182+
envp.push_back(nullptr);
183+
184+
// Re-exec instead of fork(): fork only copies the calling thread, so threads
185+
// started before the harness (e.g. in main) would be missing in the child.
186+
pid_t pid = 0;
187+
const int spawn_error = posix_spawn(&pid, program.c_str(), nullptr, nullptr,
188+
argv.data(), envp.data());
189+
if (spawn_error != 0) {
190+
std::cerr << "failed to start the process for " << uri << ": "
191+
<< std::strerror(spawn_error) << std::endl;
192+
std::exit(GENERIC_FAILURE_EXIT_CODE);
193+
}
194+
195+
int wait_status = 0;
196+
while (waitpid(pid, &wait_status, 0) < 0) {
197+
if (errno == EINTR) {
198+
continue;
199+
}
200+
std::cerr << "failed to wait for the process of " << uri << ": "
201+
<< std::strerror(errno) << std::endl;
202+
std::exit(GENERIC_FAILURE_EXIT_CODE);
203+
}
204+
205+
if (WIFEXITED(wait_status) && WEXITSTATUS(wait_status) == 0) {
206+
return;
207+
}
208+
std::exit(exit_code(wait_status));
209+
}
210+
#endif
211+
212+
} // namespace codspeed

0 commit comments

Comments
 (0)