Crafter.Build/tests/JobLimit/main.cpp

177 lines
8.8 KiB
C++
Raw Permalink Normal View History

test(build): build many units at once and count the threads it takes JobLimit makes two projects and one more for every 32 hardware threads and builds them from nothing at once, each from a thread of its own, as RunTests builds its tests, while it counts the threads of its own process. A project is 69 sources: 64 that import nothing, half C and half C++, then a module of two partitions, one importing the other, with its implementation unit, and a main.cpp that imports the module. It is the same size on every machine, so that no command of its build grows with the machine. The builds together may add as many threads as the machine has hardware threads, and have to add at least two where there are two; every program is then run and has to print 995: what its 64 C and C++ functions return and the module's Top(), which is built on the two partitions' functions. On 5b75df3 it fails: on a machine with 56 hardware threads, "3 builds of 207 sources in all ran on 205 threads at once". The count sees the steps that are jobs. A link is none: its Build() runs it through RunBuildCommand from a thread that was there before the count, which does not tell whether the link waited for a worker. JobGroup drives pools of its own, of one to four workers. Twelve jobs on three workers run three at once and no more; a job starts after the ones it was added after, in a graph of four jobs and in one of 300; the first error keeps a job that comes after it and the jobs added later from starting, and so does Fail(); what a job throws is its error; a chain gets through one worker; Run() runs its work on a worker, on the calling thread when that is one, where a JobGroup is refused; and leaving a group's scope waits for the job that runs and starts no other. It also holds the process's pool to a worker per hardware thread.
2026-11-13 17:59:55 +01:00
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
namespace fs = std::filesystem;
using namespace Crafter;
// Builds run at most as many of their steps at once as the machine has
// hardware threads, however many files are stale and however many builds run
// side by side. Build() used to start a thread for every stale unit, and
// nothing bounded how many of them ran their compiler at once, on 8 hardware
// threads as on 56.
//
// Several projects are made here and built at once, each from a thread of
// this test, as RunTests builds its tests: enough of them to have two stale
// sources and more for every hardware thread. A project is 69 sources: 64
// that import nothing, half C and half C++, then a module of two partitions,
// one importing the other, with its implementation unit, and a main.cpp that
// imports the module, so that steps waiting for other steps queue with the
// rest. It is the same size on every machine, so no command of its build
// grows with the machine; the number of projects does. While they build from
// nothing, the threads of this process are counted: a job occupies a worker
// for as long as it runs, so the builds may add as many threads as there are
// hardware threads and no more. Before, they added one per source. A link is
// no job: its Build() runs it through RunBuildCommand from a thread that was
// there before the count, which therefore does not tell whether it waited
// for a worker. Every program is then run, since a limit kept by leaving
// steps out would pass the count as well.
namespace {
std::int32_t Failures = 0;
void Check(bool cond, std::string_view msg) {
if (!cond) {
std::println(std::cerr, "FAIL: {}", msg);
++Failures;
}
}
// The threads of this process, as the kernel counts them: one read, so
// no thread is counted twice or missed between two of them.
std::int32_t ThreadCount() {
std::ifstream status("/proc/self/status");
std::string line;
while (std::getline(status, line)) {
constexpr std::string_view key = "Threads:";
if (line.starts_with(key)) return std::stoi(line.substr(key.size()));
}
return 0;
}
void Write(const fs::path& file, std::string_view text) {
std::ofstream(file, std::ios::binary | std::ios::trunc) << text;
}
// One module or import declaration of a generated source. Put together
// here because the source scanner reads one spelled out in a string
// literal as a declaration of this file's own (issue #45).
std::string Declare(std::string_view keywords, std::string_view name) {
return std::format("{} {};\n", keywords, name);
}
// The C sources of one project, and as many C++ ones.
constexpr std::int32_t PerKind = 32;
// The units of one project: those sources, the module's primary
// interface, two partitions and implementation unit, and main.cpp.
constexpr std::int32_t Units = 2 * PerKind + 5;
// What a project's program prints: every C unit returns its index and so
// does every C++ one; Top() is 3.
constexpr std::int32_t Printed = 3 + PerKind * (PerKind - 1);
// Writes one project into `root` and returns its configuration.
std::unique_ptr<Configuration> MakeProject(const fs::path& root) {
fs::create_directories(root);
std::unique_ptr<Configuration> cfg = std::make_unique<Configuration>();
cfg->path = root;
cfg->name = "job-limit";
cfg->outputName = "job-limit";
cfg->target = HostTarget();
cfg->type = ConfigurationType::Executable;
// Limit:High imports Limit:Low, the primary interface both, the
// module's implementation unit the primary interface, and main.cpp
// the module.
Write(root / "Limit-Low.cppm", std::format("{}export int Low() {{ return 1; }}\n", Declare("export module", "Limit:Low")));
Write(root / "Limit-High.cppm", std::format("{}{}export int High() {{ return Low() + 1; }}\n", Declare("export module", "Limit:High"), Declare("import", ":Low")));
Write(root / "Limit.cppm", std::format("{}{}{}export int Top();\n", Declare("export module", "Limit"), Declare("export import", ":Low"), Declare("export import", ":High")));
Write(root / "Limit-impl.cpp", std::format("{}int Top() {{ return High() + 1; }}\n", Declare("module", "Limit")));
std::string declarations;
std::string sum;
std::vector<fs::path> implementations = { "main", "Limit-impl" };
for (std::int32_t i = 0; i < PerKind; ++i) {
Write(root / std::format("c{}.c", i), std::format("int c_unit_{0}(void) {{ return {0}; }}\n", i));
// Without the extension and absolute: cFiles resolve against the
// working directory, not cfg.path.
cfg->cFiles.push_back(root / std::format("c{}", i));
Write(root / std::format("x{}.cpp", i), std::format("int cpp_unit_{0}() {{ return {0}; }}\n", i));
implementations.emplace_back(std::format("x{}", i));
declarations += std::format("extern \"C\" int c_unit_{0}(void);\nint cpp_unit_{0}();\n", i);
sum += std::format(" + c_unit_{0}() + cpp_unit_{0}()", i);
}
Write(root / "main.cpp", std::format("{}{}{}int main() {{ std::print(\"{{}}\", Top(){}); }}\n", Declare("import", "std"), Declare("import", "Limit"), declarations, sum));
std::array<fs::path, 3> interfaces = { "Limit", "Limit-Low", "Limit-High" };
cfg->GetInterfacesAndImplementations(interfaces, implementations);
return cfg;
}
}
int main() {
const std::int32_t workers = static_cast<std::int32_t>(std::max(1u, std::thread::hardware_concurrency()));
// Two projects and one more for every 32 hardware threads: 64 sources
// each, so twice as many sources as hardware threads, and more.
const std::int32_t count = workers / PerKind + 2;
const fs::path root = fs::temp_directory_path() / "crafter-build-job-limit";
fs::remove_all(root);
std::vector<std::unique_ptr<Configuration>> projects;
for (std::int32_t i = 0; i < count; ++i) projects.push_back(MakeProject(root / std::to_string(i)));
// What went wrong in each build; empty where nothing did.
std::vector<std::string> errors(projects.size());
std::atomic<bool> start{false};
std::atomic<std::int32_t> peak{0};
std::int32_t before = 0;
{
std::jthread sampler([&peak](std::stop_token stop) {
while (!stop.stop_requested()) {
const std::int32_t seen = ThreadCount();
if (seen > peak.load()) peak.store(seen);
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
});
std::vector<std::jthread> builders;
for (std::size_t i = 0; i < projects.size(); ++i) {
builders.emplace_back([&projects, &errors, &start, i] {
start.wait(false);
try {
std::unordered_map<fs::path, std::shared_future<BuildResult>> depResults;
std::mutex depMutex;
errors[i] = Build(*projects[i], depResults, depMutex).result;
} catch (const std::exception& e) {
errors[i] = std::format("Build() threw: {}", e.what());
}
});
}
// With the sampler running and every builder waiting to start, so
// that they are part of what was there before the builds.
before = ThreadCount();
start = true;
start.notify_all();
// Leaving the scope joins the builders, then stops the sampler.
}
const std::int32_t added = peak.load() - before;
bool built = true;
for (std::size_t i = 0; i < projects.size(); ++i) {
Check(errors[i].empty(), std::format("the build of project {} failed: {}", i, errors[i]));
built = built && errors[i].empty();
}
Check(added <= workers, std::format("{} builds of {} sources in all ran on {} threads at once, on a machine with {} hardware threads", count, count * Units, added, workers));
// The other way round: builds that ran one step at a time would keep
// the limit too.
Check(added >= std::min(workers, 2), std::format("the builds never had two steps running at once: {} thread(s) at most, with {} hardware threads", added, workers));
if (built) {
for (std::size_t i = 0; i < projects.size(); ++i) {
const auto run = RunCommandWithTimeout(ShellQuote(ExpectedOutput(*projects[i]).string()), std::chrono::seconds(30));
Check(run.exitCode == 0 && run.output == std::to_string(Printed), std::format("the program of project {} printed '{}' (exit {}), expected {}: a unit is missing from it or was built out of order", i, run.output, run.exitCode, Printed));
}
}
return Failures == 0 ? 0 : 1;
}