diff --git a/project.cpp b/project.cpp index 82eb74b..f3518dd 100644 --- a/project.cpp +++ b/project.cpp @@ -334,6 +334,8 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("DependencyNotes").Dependencies({ CrafterBuildLib.get() }) .LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl"); cfg.AddTest("ConcurrentDependencyReset").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("JobGroup").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("JobLimit").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("ImportCycle").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); } diff --git a/tests/JobGroup/main.cpp b/tests/JobGroup/main.cpp new file mode 100644 index 0000000..970837b --- /dev/null +++ b/tests/JobGroup/main.cpp @@ -0,0 +1,308 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +using namespace Crafter; + +// JobPool and JobGroup, which every build step runs on. A pool runs as many +// jobs at once as it has workers and no more; a job of a group starts when the +// jobs it was added after have finished; the first error keeps what has not +// started from starting; and nothing that waits for jobs does so on a worker, +// where it would keep from them the thread they need. +// +// The pools here are the test's own, of one to four workers, so what is +// counted does not depend on the machine. Build() runs on the process's pool: +// tests/JobLimit holds a whole build to that one. + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + // Twelve jobs on three workers. Each holds its worker until three run at + // once, so the pool is seen to reach its limit however the threads are + // scheduled, and then a moment longer with the lock released, counted as + // running all the while: jobs a pool let in beyond its workers would be + // counted on top of the ones in that moment. A pool that never gets to + // three is waited on once, then given up on. + void RunsAsManyAsItHasWorkers() { + constexpr std::int32_t workers = 3; + constexpr std::int32_t count = 12; + JobPool pool(workers); + std::mutex mutex; + std::condition_variable changed; + std::int32_t running = 0; + std::int32_t peak = 0; + std::int32_t ran = 0; + bool gaveUp = false; + JobGroup jobs(pool); + for (std::int32_t i = 0; i < count; ++i) { + jobs.Add(std::format("gauge {}", i), [&]() -> std::string { + std::unique_lock lock(mutex); + ++running; + peak = std::max(peak, running); + changed.notify_all(); + if (!changed.wait_for(lock, std::chrono::seconds(20), [&] { return peak >= workers || gaveUp; })) gaveUp = true; + lock.unlock(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + lock.lock(); + --running; + ++ran; + return {}; + }); + } + Check(jobs.Wait().empty(), "jobs that return nothing leave the group without an error"); + Check(ran == count, std::format("every job runs: {} of {} did", ran, count)); + Check(peak == workers, std::format("a pool of {} workers runs {} jobs at once, not {}", workers, workers, peak)); + } + + // a, then b and c, then d: each records when it runs. The ones that + // others wait for take a moment first, so a group that started everything + // at once would record them last. + void StartsAJobAfterTheOnesItComesAfter() { + JobPool pool(3); + std::mutex mutex; + std::vector order; + const auto record = [&mutex, &order](std::string name, std::int32_t milliseconds) { + return [&mutex, &order, name = std::move(name), milliseconds]() -> std::string { + std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); + std::lock_guard lock(mutex); + order.push_back(name); + return {}; + }; + }; + const auto position = [&order](std::string_view name) { + return std::ranges::find(order, name) - order.begin(); + }; + JobGroup jobs(pool); + const JobGroup::Job a = jobs.Add("a", record("a", 60)); + const std::array afterA = {a}; + const JobGroup::Job b = jobs.Add("b", record("b", 30), afterA); + const JobGroup::Job c = jobs.Add("c", record("c", 0), afterA); + const std::array afterBoth = {b, c}; + const JobGroup::Job d = jobs.Add("d", record("d", 0), afterBoth); + Check(jobs.Wait().empty(), "the ordered jobs leave no error"); + Check(order.size() == 4, std::format("all four ordered jobs run: {}", order)); + Check(position("a") < position("b") && position("a") < position("c"), std::format("b and c start after a has finished: {}", order)); + Check(position("b") < position("d") && position("c") < position("d"), std::format("d starts after both b and c have finished: {}", order)); + + // After jobs that finished long ago: nothing is left to release it, + // so it has to start by itself. + const std::array afterDone = {a, d}; + jobs.Add("e", record("e", 0), afterDone); + Check(jobs.Wait().empty() && order.size() == 5, std::format("a job added after finished jobs runs: {}", order)); + + bool refused = false; + try { + const std::array afterNone = {JobGroup::Job(99)}; + jobs.Add("f", record("f", 0), afterNone); + } catch (const std::out_of_range&) { + refused = true; + } + Check(refused, "a job cannot be added after one the group does not have"); + Check(jobs.Wait().empty() && order.size() == 5, std::format("the refused job never runs: {}", order)); + } + + // Three hundred jobs on four workers, each after up to three picked among + // the ones added before it, the same pick every run: every job runs + // once, and none before a job it comes after has finished. + void KeepsTheOrderOfALargerGraph() { + constexpr std::int32_t count = 300; + JobPool pool(4); + std::vector> runs(count); + std::atomic early{0}; + std::mt19937 random(20261112); + JobGroup jobs(pool); + std::vector added; + for (std::int32_t i = 0; i < count; ++i) { + std::vector after; + std::vector before; + for (std::int32_t pick = 0; i > 0 && pick < 3; ++pick) { + if (random() % 2 == 0) continue; + const std::int32_t chosen = static_cast(random() % static_cast(i)); + after.push_back(added[chosen]); + before.push_back(chosen); + } + added.push_back(jobs.Add(std::format("node {}", i), [&runs, &early, before = std::move(before), i]() -> std::string { + for (const std::int32_t earlier : before) { + if (runs[earlier].load() != 1) ++early; + } + ++runs[i]; + return {}; + }, after)); + } + Check(jobs.Wait().empty(), "the larger graph leaves no error"); + const std::int64_t once = std::ranges::count_if(runs, [](const std::atomic& ran) { return ran.load() == 1; }); + Check(once == count, std::format("each of {} jobs runs once: {} did", count, once)); + Check(early.load() == 0, std::format("no job starts before the ones it comes after have finished: {} did", early.load())); + } + + void TheFirstErrorStopsTheRest() { + JobPool pool(2); + { + JobGroup jobs(pool); + std::atomic dependentRan{false}; + std::atomic lateRan{false}; + const JobGroup::Job failing = jobs.Add("failing", [] { return std::string("boom"); }); + const std::array afterFailing = {failing}; + jobs.Add("dependent", [&dependentRan]() -> std::string { + dependentRan = true; + return {}; + }, afterFailing); + Check(jobs.Wait() == "boom", "Wait returns what the failed job returned"); + Check(jobs.Failed(), "a group with a failed job has failed"); + Check(!dependentRan, "a job that comes after a failed one does not run"); + jobs.Add("late", [&lateRan]() -> std::string { + lateRan = true; + return {}; + }); + jobs.Add("second", [] { return std::string("second"); }); + Check(jobs.Wait() == "boom", "the first error stays the group's error"); + Check(!lateRan, "a job added to a failed group does not run"); + } + { + JobGroup jobs(pool); + jobs.Add("thrower", []() -> std::string { throw std::runtime_error("bang"); }); + const std::string error = jobs.Wait(); + Check(error == "thrower: bang", std::format("what a job throws is its error, under its label: '{}'", error)); + } + { + JobGroup jobs(pool); + std::atomic ran{false}; + Check(!jobs.Failed(), "a new group has not failed"); + jobs.Fail("outside"); + jobs.Fail("again"); + jobs.Add("after", [&ran]() -> std::string { + ran = true; + return {}; + }); + Check(jobs.Wait() == "outside", "Fail gives the group its error, the first time"); + Check(!ran, "no job starts in a group failed from outside"); + } + } + + // One worker and jobs that wait for each other: a job held back costs no + // thread, so the chain gets through on the one there is. + void OneWorkerIsEnough() { + JobPool pool(1); + std::mutex mutex; + std::int32_t running = 0; + std::int32_t peak = 0; + std::vector order; + JobGroup jobs(pool); + std::vector previous; + for (std::int32_t i = 0; i < 6; ++i) { + const auto work = [&mutex, &running, &peak, &order, i]() -> std::string { + { + std::lock_guard lock(mutex); + ++running; + peak = std::max(peak, running); + } + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + std::lock_guard lock(mutex); + --running; + order.push_back(i); + return {}; + }; + // Every second one independent of the chain. + const JobGroup::Job job = i % 2 == 0 ? jobs.Add(std::format("link {}", i), work, previous) : jobs.Add(std::format("free {}", i), work); + if (i % 2 == 0) previous = {job}; + } + Check(jobs.Wait().empty(), "the chain on one worker leaves no error"); + Check(order.size() == 6 && peak == 1, std::format("six jobs run one at a time on one worker: {} ran, {} at once", order.size(), peak)); + const auto position = [&order](std::int32_t i) { + return std::ranges::find(order, i) - order.begin(); + }; + Check(position(0) < position(2) && position(2) < position(4), std::format("the chain runs in its order: {}", order)); + } + + void RunIsOneJob() { + JobPool pool(1); + const std::thread::id here = std::this_thread::get_id(); + std::thread::id ranOn = here; + pool.Run([&ranOn] { ranOn = std::this_thread::get_id(); }); + Check(ranOn != here, "Run runs the work on a worker and returns once it has"); + + bool rethrown = false; + try { + pool.Run([] { throw std::runtime_error("from the work"); }); + } catch (const std::runtime_error& e) { + rethrown = std::string_view(e.what()) == "from the work"; + } + Check(rethrown, "what the work throws, Run throws"); + + // On the pool's only worker: queued, the inner step would wait for + // the thread its caller holds. + std::thread::id outer; + std::thread::id inner; + JobGroup jobs(pool); + jobs.Add("outer", [&pool, &outer, &inner]() -> std::string { + outer = std::this_thread::get_id(); + pool.Run([&inner] { inner = std::this_thread::get_id(); }); + return {}; + }); + Check(jobs.Wait().empty() && outer == inner && outer != here, "Run on a worker of the pool runs the work on that worker"); + + // And a group there is refused, where it would have waited the same way. + jobs.Add("nested", [&pool]() -> std::string { + JobGroup nested(pool); + return {}; + }); + const std::string error = jobs.Wait(); + Check(error.starts_with("nested: ") && error.contains("JobGroup"), std::format("a JobGroup on a worker of its own pool is refused: '{}'", error)); + } + + // Leaving the scope of a group without Wait(), as an early return does: + // the job that runs is waited for, the one behind it never starts. The + // scope is left once the first runs, and the first goes on until the + // group has failed, which is what its destructor does first, so the + // second cannot have started before. + void LeavingWaitsForWhatRuns() { + JobPool pool(1); + std::atomic firstStarted{false}; + std::atomic firstFinished{false}; + std::atomic secondRan{false}; + { + JobGroup jobs(pool); + jobs.Add("first", [&jobs, &firstStarted, &firstFinished]() -> std::string { + firstStarted = true; + firstStarted.notify_all(); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20); + while (!jobs.Failed() && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + firstFinished = true; + return {}; + }); + jobs.Add("second", [&secondRan]() -> std::string { + secondRan = true; + return {}; + }); + firstStarted.wait(false); + } + Check(firstFinished, "leaving a group waits for the job that is running"); + Check(!secondRan, "leaving a group keeps the jobs that have not started from starting"); + } +} + +int main() { + // The labels of a few dozen jobs say nothing here. + Progress::SetVerbosity(Progress::Verbosity::Quiet); + + const std::uint32_t hardware = std::max(1u, std::thread::hardware_concurrency()); + Check(JobPool::Process().Workers() == hardware, std::format("the process's pool has a worker per hardware thread: {} for {}", JobPool::Process().Workers(), hardware)); + Check(JobPool(0).Workers() == 1, "a pool has at least one worker"); + + RunsAsManyAsItHasWorkers(); + StartsAJobAfterTheOnesItComesAfter(); + KeepsTheOrderOfALargerGraph(); + TheFirstErrorStopsTheRest(); + OneWorkerIsEnough(); + RunIsOneJob(); + LeavingWaitsForWhatRuns(); + return Failures == 0 ? 0 : 1; +} diff --git a/tests/JobLimit/main.cpp b/tests/JobLimit/main.cpp new file mode 100644 index 0000000..a6ce449 --- /dev/null +++ b/tests/JobLimit/main.cpp @@ -0,0 +1,177 @@ +// 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 MakeProject(const fs::path& root) { + fs::create_directories(root); + std::unique_ptr cfg = std::make_unique(); + 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 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 interfaces = { "Limit", "Limit-Low", "Limit-High" }; + cfg->GetInterfacesAndImplementations(interfaces, implementations); + return cfg; + } +} + +int main() { + const std::int32_t workers = static_cast(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> 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 errors(projects.size()); + std::atomic start{false}; + std::atomic 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 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> 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; +}