// 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; }