feat(build): run a build's steps on one worker per hardware thread

Build() started a thread for every stale shader, asset, C, CUDA and C++
unit, and Module::Compile one more for every stale partition, and
nothing bounded how many of them ran their step at once. Jorijn asked
for the amount of parallelism to be limited by the amount of threads
instead of just starting one per file; the threads are taken here to be
the machine's hardware threads.

The new :Jobs partition holds the two pieces. JobPool is worker threads
behind one queue, started as jobs need them up to a fixed number, and
JobPool::Process() is the pool of the process: at most a worker per
hardware thread, one where std:🧵:hardware_concurrency does not
know. JobGroup is the jobs of one build on a pool. A job starts once
the jobs it was added after have finished; the first job to fail keeps
the ones that have not started from starting, and Wait() returns its
error. No job waits for another job, and a JobGroup made on a worker of
its own pool throws: a worker that waited for a job still in the queue
would hold the thread that job needs.

Build() adds what it did on those threads to a JobGroup instead, and
the group's first error replaces the buildCancelled and buildError pair
the threads set. The module units no longer block on the `compiled`
flag of the units they import: Schedule() replaces Compile() on Module,
ModulePartition and Implementation and adds a unit's jobs after the jobs
that write the BMIs it imports. An interface unit is two jobs, its BMI
and then its object from the BMI, so the units importing it start when
the first is done, as they did when one thread ran both commands and
raised the flag in between. A primary interface now waits for the BMIs
of its partitions and no longer for their objects. Each of the two jobs
has a progress line, "Precompiling X.cppm" and "Compiling X.cppm" for
every interface unit, where a module and its partitions shared one
"Compiling interface X".

RunBuildCommand runs its command on a worker of the process's pool: on
the calling thread when that is one, otherwise it waits for one. A link,
an archive, the std module's precompile and project.cpp's compile are
steps under the limit that way. The threads Build() starts per
dependency and per external dependency stay: one of the first runs the
dependency's own Build(), or waits for the thread that does, and one of
the second runs git and cmake.

With the BMI and the object as two jobs, a build that fails between them
has written the BMI and skips the object, and Check, which reads
staleness off the BMI, would call the unit built from then on.
Schedule() therefore adds the object job alone for a unit whose BMI is
up to date and whose object is missing or older than the BMI. A build
interrupted between the two commands, or one whose second command
failed, left the same behind before, and it stayed: the link took the
object of the source before the edit, or failed on the missing one.

ImportCycleError is now what keeps Schedule() from following a round of
imports without end.

The limit is on steps. Outside it, as AGENTS.template.md lists: an
ExternalDependency's cmake --build, which keeps its own --parallel of
as many jobs as there are hardware threads; the tests RunTests runs,
--jobs= of them at once as before; the Crafter.Build modules
EnsureCrafterBuildPcms precompiles one after another; and the threads a
step starts for itself, which lld does for a link and Crafter.Asset's
GDeflate compressor for an asset. The pool is one process's. The --help
text says what a build runs at once and that test --jobs= counts tests.

ConcurrentDependencyReset read the `compiled` flag, which is gone. It
asserts on `checked` and `scheduled` instead, the state a reset from
another build's thread would clear now, with a unit scheduled twice as
the result, and the comment in its fixture says what the implementation
unit comes after now. TransitiveInterfaceChange's comment names
Schedule() where it named Compile() as what honours a partition's
imports. Two comments in :Platform that spoke of worker threads, a word
that now means the pool's, name the threads they mean. The bug-prover
lens's section said shaders compile on a thread of their own each, and
describes the pool now.
This commit is contained in:
Jorijn van der Graaf 2026-11-13 17:59:55 +01:00
commit 913310da86
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
19 changed files with 726 additions and 377 deletions

View file

@ -0,0 +1,218 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Crafter.Build:Jobs_impl;
import std;
import :Jobs;
import :Progress;
namespace {
// The pool this thread is a worker of; null on every other thread.
thread_local const Crafter::JobPool* WorkerOf = nullptr;
}
namespace Crafter {
JobPool::JobPool(std::uint32_t workers) : limit(std::max(workers, 1u)) {}
JobPool::~JobPool() {
{
std::lock_guard lock(mutex);
stopping = true;
}
wake.notify_all();
for (std::thread& thread : threads) thread.join();
}
JobPool& JobPool::Process() {
static JobPool* const pool = new JobPool(std::thread::hardware_concurrency());
return *pool;
}
std::uint32_t JobPool::Workers() const {
return limit;
}
void JobPool::Submit(std::function<void()> job) {
std::lock_guard lock(mutex);
queue.push_back(std::move(job));
if (queue.size() <= idle || threads.size() >= limit) {
wake.notify_one();
return;
}
try {
threads.emplace_back([this] { Work(); });
} catch (...) {
// The system has no thread to give. The workers there are take
// the job when they get to it. With none it would stay queued
// for good, and whoever waits for it with it.
if (!threads.empty()) return;
queue.pop_back();
throw;
}
}
void JobPool::Work() {
WorkerOf = this;
std::unique_lock lock(mutex);
for (;;) {
while (queue.empty() && !stopping) {
++idle;
wake.wait(lock);
--idle;
}
if (queue.empty()) return;
std::function<void()> job = std::move(queue.front());
queue.pop_front();
lock.unlock();
job();
// Before the lock is taken again: what the job captured is
// released without holding up the queue.
job = nullptr;
lock.lock();
}
}
void JobPool::Run(const std::function<void()>& work) {
if (WorkerOf == this) {
work();
return;
}
// Shared with the job, not a local of this function: this thread
// goes on as soon as the value is set, which is before set_value has
// returned on the worker.
const std::shared_ptr<std::promise<void>> done = std::make_shared<std::promise<void>>();
std::future<void> finished = done->get_future();
Submit([&work, done] {
try {
work();
done->set_value();
} catch (...) {
done->set_exception(std::current_exception());
}
});
finished.get();
}
struct JobGroup::Node {
std::string label;
std::function<std::string()> work;
std::unique_ptr<Progress::Task> task;
// The jobs added after this one that it has yet to release, and how
// many jobs this one still waits for. Both under the group's mutex;
// the members above belong to whoever runs the job.
std::vector<Node*> dependents;
std::size_t waiting = 0;
bool finished = false;
};
JobGroup::JobGroup(JobPool& pool) : pool(pool) {
if (WorkerOf == &pool) throw std::logic_error("a JobGroup cannot be made on a worker of its own pool: it would wait there for jobs that need that worker");
}
JobGroup::~JobGroup() {
std::unique_lock lock(mutex);
failed = true;
settled.wait(lock, [this] { return unfinished == 0; });
}
JobGroup::Job JobGroup::Add(std::string label, std::function<std::string()> work, std::span<const Job> after) {
std::unique_ptr<Node> made = std::make_unique<Node>();
// Counted from here on, not from when it starts: the total a build
// shows is then what it has queued, and not only what the workers
// have got to.
made->task = std::make_unique<Progress::Task>(label);
made->label = std::move(label);
made->work = std::move(work);
std::lock_guard lock(mutex);
// Room for the new job in each list it may join, made before the
// group knows of it: from there to the count below nothing can throw,
// so no job is ever waited on by half of what it comes after.
for (const Job job : after) {
if (job >= nodes.size()) throw std::out_of_range("JobGroup::Add: a job can only come after jobs added before it");
std::vector<Node*>& dependents = nodes[job]->dependents;
dependents.reserve(dependents.size() + after.size());
}
const Job id = nodes.size();
Node& node = *nodes.emplace_back(std::move(made));
for (const Job job : after) {
Node& before = *nodes[job];
if (before.finished) continue;
before.dependents.push_back(&node);
++node.waiting;
}
++unfinished;
if (node.waiting != 0) return id;
try {
Start(node);
} catch (...) {
// Not queued (JobPool::Submit), so nothing will ever finish it:
// it is taken back, or Wait() would never return.
node.work = nullptr;
node.task.reset();
node.finished = true;
if (--unfinished == 0) settled.notify_all();
throw;
}
return id;
}
void JobGroup::Start(Node& node) {
pool.Submit([this, &node] { Execute(node); });
}
void JobGroup::Execute(Node& node) {
bool skipped = false;
{
std::lock_guard lock(mutex);
skipped = failed;
}
std::string result;
if (!skipped) {
try {
result = node.work();
} catch (const std::exception& e) {
result = std::format("{}: {}", node.label, e.what());
} catch (...) {
result = std::format("{}: threw something that isn't a std::exception", node.label);
}
}
// Both before the group hears of it: what the work captured is gone,
// and the step counted as done, by the time Wait() returns.
node.work = nullptr;
node.task.reset();
// Nothing of the group is touched once this lock is released: with
// the last job finished, whoever waited may destroy it.
std::lock_guard lock(mutex);
if (!result.empty() && !failed) {
failed = true;
error = std::move(result);
}
node.finished = true;
// Released after a failure as well: they are skipped when they run,
// which is what counts them as finished.
for (Node* dependent : node.dependents) {
if (--dependent->waiting == 0) Start(*dependent);
}
if (--unfinished == 0) settled.notify_all();
}
void JobGroup::Fail(std::string why) {
std::lock_guard lock(mutex);
if (failed) return;
failed = true;
error = std::move(why);
}
bool JobGroup::Failed() const {
std::lock_guard lock(mutex);
return failed;
}
std::string JobGroup::Wait() {
std::unique_lock lock(mutex);
settled.wait(lock, [this] { return unfinished == 0; });
return error;
}
}