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

@ -13,9 +13,25 @@ The execution contexts to enumerate, beside the charter's:
Running a test or a built artifact is a shell command too (`:Test`, Running a test or a built artifact is a shell command too (`:Test`,
`:Clang`). A path, file name or flag that reaches one with a space or a `:Clang`). A path, file name or flag that reaches one with a space or a
shell metacharacter in it is an input to attack. Other steps run inside shell metacharacter in it is an input to attack. Other steps run inside
the process, among them glslang's shader compiles, on a thread of their the process, among them glslang's shader compiles (`:Shader`), the
own per stale shader (`:Shader`), and lint's parse through the libclang compression of an asset in Crafter.Asset, which starts threads of its own
the linter dlopens (`:Lint`). (`:Asset`), and lint's parse through the libclang the linter dlopens
(`:Lint`).
- A build's steps run as jobs on the workers of `JobPool::Process()`
(`:Jobs`): up to as many threads as the machine has hardware threads, one
where that is one or unknown. The compiles of a configuration's stale
shaders, C, CUDA and C++ units, the compression of its stale assets, and
its copies of `cfg.files` and of the other files of an asset directory
go through the `JobGroup` of its `Build()`, which starts a job once the
jobs it was added after have finished; a `RunBuildCommand` waits for a
worker when its caller is not one. Jobs are waited for by threads that
are not workers, among them one that runs a `Build()` (its caller's, one
of `RunTests`', one a `Build()` starts per dependency) and the one that
runs `LoadProject`, for the compiles of the std module and of
`project.cpp`. The threads a `Build()` starts per external dependency are
not workers either and wait for no job: they run git and cmake. An
executable's copies of what its dependencies forward run on the thread of
its `Build()`.
- Several crafter-build processes share `~/.cache/crafter.build/` at once: - Several crafter-build processes share `~/.cache/crafter.build/` at once:
the std and Crafter.Build PCMs per target and march (the the std and Crafter.Build PCMs per target and march (the
`ConcurrentCacheRace` test), and the external clones with their `.lock` `ConcurrentCacheRace` test), and the external clones with their `.lock`

View file

@ -26,7 +26,8 @@ Partitions and what they own:
- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. - `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages.
- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. - `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types.
- `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code. - `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code.
- `:Interface` and `:Implementation` model module units, their staleness checks and their compiles. - `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`.
- `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`).
- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. - `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`.
- `:Test` holds `AddTest`, `RunTests` and `TestRunner`. - `:Test` holds `AddTest`, `RunTests` and `TestRunner`.
- `:Lint` is the lint/format driver plus the libclang token and AST layer. - `:Lint` is the lint/format driver plus the libclang token and AST layer.
@ -121,6 +122,7 @@ Beyond the rules:
- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule. - Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule.
- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. - There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests.
- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. - A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`.
- Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its `JobGroup` in `Build()`, after the jobs whose output it reads; run a step that stands by itself, as a link does, through `RunBuildCommand`, which runs on a worker of `JobPool::Process()` whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: a `JobGroup` made on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group.
- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. - Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`.
- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. - Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory.
@ -198,6 +200,8 @@ Local builds are two scripts in `project.cpp`. Run them with the native binary:
- A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. - A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away.
- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. - A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard.
- `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. - `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache.
- The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel <hardware threads>` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own.
- An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which 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 that fails between the two jobs leaves a unit like that, since no job starts after a failure.
- The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then. - The source scanner follows an `import` it reads in a string literal or under `#if 0` like any other (issue #45), so interface units can import each other by its account alone. `ImportCycleError` refuses such a round, naming the units, at the top of the `Build()` of the configuration whose units form it: before that configuration makes a directory or builds a dependency, though a configuration built on it has started its own build by then.
- Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. - Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are.
- A CMake external whose recorded configure inputs (`<build>/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. - A CMake external whose recorded configure inputs (`<build>/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached.

View file

@ -47,7 +47,7 @@ cp wasi-runtime/index.html.in share/crafter-build/wasi-runtime/
# Partition order is the import order: every unit is listed before the # Partition order is the import order: every unit is listed before the
# units that import it, and the umbrella last. # units that import it, and the umbrella last.
PARTITIONS="Toolchain Shader Platform Flatpak Interface Implementation External Agents Clang Test Lint Script Progress Asset" PARTITIONS="Toolchain Shader Platform Flatpak Jobs Interface Implementation External Agents Clang Test Lint Script Progress Asset"
cp interfaces/Crafter.Build.cppm share/crafter-build/ cp interfaces/Crafter.Build.cppm share/crafter-build/
for p in $PARTITIONS; do for p in $PARTITIONS; do

View file

@ -17,6 +17,7 @@ import :Agents;
import :Progress; import :Progress;
import :Asset; import :Asset;
import :Flatpak; import :Flatpak;
import :Jobs;
namespace fs = std::filesystem; namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
@ -148,8 +149,8 @@ void Configuration::GetInterfacesAndImplementations(std::span<fs::path> interfac
// Primary interface unit: record only its module imports. Its // Primary interface unit: record only its module imports. Its
// `[export] import :Part;` lines need no edge — Module::Check walks // `[export] import :Part;` lines need no edge — Module::Check walks
// every partition it owns and Module::Compile builds them all before // every partition it owns and Module::Schedule puts the primary
// precompiling itself, so partitions are covered wholesale. // interface after all of them, so partitions are covered wholesale.
if (partition == nullptr) { if (partition == nullptr) {
std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)");
std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern); std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern);
@ -537,9 +538,10 @@ namespace {
// to the first again: partitions that import each other, a partition that // to the first again: partitions that import each other, a partition that
// imports its own module, sibling modules that import each other. Empty // imports its own module, sibling modules that import each other. Empty
// when there are none, otherwise the error naming the round. No order // when there are none, otherwise the error naming the round. No order
// builds such units: each is compiled on a thread that first waits for // builds such units. Schedule() works the order out before it adds a
// the units it imports, a primary interface for the partitions of its // unit's jobs, by following the imports, and would follow a round of
// module as well, so such a build hung with no compiler running. // them without end. When each unit had a thread that waited for the
// units it imports, such a build hung with no compiler running.
// //
// The imports are the scanner's, which reads one in a string literal, in // The imports are the scanner's, which reads one in a string literal, in
// a comment that spans lines or under `#if 0` as it reads any other // a comment that spans lines or under `#if 0` as it reads any other
@ -767,22 +769,26 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// (diamond deps point at the same Configuration*), and every config in the // (diamond deps point at the same Configuration*), and every config in the
// tree gets its own Build() call: the per-PcmDir builder registered in // tree gets its own Build() call: the per-PcmDir builder registered in
// depResults resets its own state here, at the top of its own Build(), // depResults resets its own state here, at the top of its own Build(),
// sequenced before that config's compile threads spawn. Recursing into // sequenced before that config's units are checked and scheduled.
// dependencies from here would re-clear a shared dependency's `compiled` // Recursing into dependencies from here would clear a shared dependency's
// atomic from a parent/sibling thread *while that dependency's own Build() // state from a parent/sibling thread *while that dependency's own Build()
// is concurrently compiling it* — after its module-compile thread set the // is using it*: a unit whose `scheduled` is cleared between two of that
// flag true and exited but before its impl/partition waiter ran // build's Schedule() calls is scheduled a second time, and two compilers
// compiled.wait(false). The waiter would then block forever on a flag // write one BMI. When every unit had a thread of its own that waited on a
// nothing re-signals: the build freezes mid-compile, idle, with no compiler // `compiled` flag of each unit it imports, the reset cleared that flag
// under a waiter, which then blocked forever on a flag nothing
// re-signalled: the build froze mid-compile, idle, with no compiler
// process alive (issue #16). Cross-config module state is consulted only via // process alive (issue #16). Cross-config module state is consulted only via
// PCM file mtimes and the depResults futures, never via these flags, so the // PCM file mtimes and the depResults futures, never via this state, so the
// narrower reset is correct. // narrower reset is correct.
for (auto& iface : config.interfaces) { for (auto& iface : config.interfaces) {
iface->checked = false; iface->checked = false;
iface->compiled.store(false); iface->scheduled = false;
iface->precompileJob.reset();
for (auto& part : iface->partitions) { for (auto& part : iface->partitions) {
part->checked = false; part->checked = false;
part->compiled.store(false); part->scheduled = false;
part->precompileJob.reset();
} }
} }
@ -874,7 +880,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// glslang #include search paths for every shader compiled in this // glslang #include search paths for every shader compiled in this
// configuration: each transitive (incl. self) buildFiles entry's parent // configuration: each transitive (incl. self) buildFiles entry's parent
// dir, or the entry itself if it points at a directory. Collected once // dir, or the entry itself if it points at a directory. Collected once
// up front so the per-shader threads can capture the resulting span by // up front so the per-shader jobs can capture the resulting span by
// reference. No file copy involved — glslang reads the includes in // reference. No file copy involved — glslang reads the includes in
// place from the dep's source tree. // place from the dep's source tree.
std::vector<fs::path> shaderIncludeDirs; std::vector<fs::path> shaderIncludeDirs;
@ -894,11 +900,23 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
collect(&config); collect(&config);
} }
std::vector<std::thread> threads; // A stale shader, asset to compress, C, CUDA or C++ unit is a job of this
threads.reserve(config.shaders.size() + 1 + config.interfaces.size() + config.implementations.size()); // group; each used to get a thread of its own the moment it was found
// stale. The copies of cfg.files and of the other files of an asset
// directory are jobs as well. The jobs run on the workers every build of
// the process shares, so no more of them run at once than the machine
// has hardware threads.
//
// The group also holds the first error among its jobs and what this
// build reports to it (Fail), the dependency and external builds below
// among it, and none of its jobs starts after one. What goes wrong once
// the jobs are done, at the link, is not the group's.
//
// Declared after everything its jobs use by reference: leaving Build()
// waits for them before any of that is destroyed. A job gets a copy of
// whatever it uses that is declared below here.
JobGroup jobs;
std::string buildError;
std::atomic<bool> buildCancelled{false};
// Two entries with the same output name would compile in parallel into // Two entries with the same output name would compile in parallel into
// one file: whichever finished last won, the build reported success, and // one file: whichever finished last won, the build reported success, and
// Check() then called both up to date. The usual way in is one source // Check() then called both up to date. The usual way in is one source
@ -909,28 +927,18 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
for (const Shader& shader : config.shaders) { for (const Shader& shader : config.shaders) {
const auto [existing, inserted] = outputs.emplace(shader.OutputName().string(), &shader); const auto [existing, inserted] = outputs.emplace(shader.OutputName().string(), &shader);
if (inserted) continue; if (inserted) continue;
buildError = std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first); jobs.Fail(std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first));
buildCancelled.store(true);
break; break;
} }
} }
for (const Shader& shader : config.shaders) { for (const Shader& shader : config.shaders) {
if (buildCancelled.load(std::memory_order_relaxed)) break; if (jobs.Failed()) break;
place(outputDir / shader.OutputName(), {}); place(outputDir / shader.OutputName(), {});
if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue; if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue;
threads.emplace_back([&shader, &outputDir, &buildDir, &shaderIncludeDirs, &buildError, &buildCancelled]() { // A source registered more than once shows up once per variant;
// A source registered more than once shows up once per variant; // name the variant so the lines can be told apart.
// name the variant so the lines can be told apart. jobs.Add(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant), [&shader, &outputDir, &buildDir, &shaderIncludeDirs] {
Progress::Task task(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant)); return shader.Compile(outputDir, buildDir, shaderIncludeDirs);
if (buildCancelled.load(std::memory_order_relaxed)) return;
std::string result = shader.Compile(outputDir, buildDir, shaderIncludeDirs);
if (result.empty()) return;
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}); });
} }
@ -942,23 +950,19 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// trees keep their nested layout so mod.json paths like // trees keep their nested layout so mod.json paths like
// "cannon/base.cmesh" resolve correctly at runtime. // "cannon/base.cmesh" resolve correctly at runtime.
// Skipped per-file if the output is newer than the source. Each // Skipped per-file if the output is newer than the source. Each
// compress runs in its own thread; passthrough copies are bundled into // compress is a job of its own; passthrough copies are bundled into
// a single thread to match the cfg.files pattern. // a single job to match the cfg.files pattern.
auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) { auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) {
place(outputDir / outRelative, {}); place(outputDir / outRelative, {});
fs::path out = outputDir / outRelative; fs::path out = outputDir / outRelative;
if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return; if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return;
threads.emplace_back([sourcePath = std::move(sourcePath), out = std::move(out), &buildError, &buildCancelled]() { // Named before the job takes the path: the arguments of one call
Progress::Task task(std::format("Compressing asset {}", sourcePath.filename().string())); // are evaluated in no particular order.
if (buildCancelled.load(std::memory_order_relaxed)) return; std::string label = std::format("Compressing asset {}", sourcePath.filename().string());
jobs.Add(std::move(label), [sourcePath = std::move(sourcePath), out = std::move(out)] {
std::error_code ec; std::error_code ec;
fs::create_directories(out.parent_path(), ec); fs::create_directories(out.parent_path(), ec);
std::string result = CompressAsset(sourcePath, out); return CompressAsset(sourcePath, out);
if (result.empty()) return;
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}); });
}; };
std::vector<std::pair<fs::path, fs::path>> assetPassthroughs; std::vector<std::pair<fs::path, fs::path>> assetPassthroughs;
@ -978,73 +982,58 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} else { } else {
std::optional<fs::path> outName = CompressedAssetName(asset); std::optional<fs::path> outName = CompressedAssetName(asset);
if (!outName) { if (!outName) {
buildCancelled.store(true); jobs.Fail(std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string()));
buildError = std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string());
break; break;
} }
submitCompress(asset, *outName); submitCompress(asset, *outName);
} }
} }
if (!assetPassthroughs.empty()) { if (!assetPassthroughs.empty()) {
threads.emplace_back([passthroughs = std::move(assetPassthroughs), &outputDir, &buildCancelled, &buildError]() { // What a copy throws is the job's error (JobGroup::Add), here and
Progress::Task task("Copying asset passthrough files"); // for cfg.files below.
if (buildCancelled.load(std::memory_order_relaxed)) return; jobs.Add("Copying asset passthrough files", [passthroughs = std::move(assetPassthroughs), &outputDir]() -> std::string {
try { for (const auto& [src, rel] : passthroughs) {
for (const auto& [src, rel] : passthroughs) { fs::path dst = outputDir / rel;
fs::path dst = outputDir / rel; fs::create_directories(dst.parent_path());
fs::create_directories(dst.parent_path()); if (!fs::exists(dst)) {
if (!fs::exists(dst)) { fs::copy_file(src, dst);
fs::copy_file(src, dst); } else if (fs::last_write_time(src) > fs::last_write_time(dst)) {
} else if (fs::last_write_time(src) > fs::last_write_time(dst)) { fs::copy_file(src, dst, fs::copy_options::overwrite_existing);
fs::copy_file(src, dst, fs::copy_options::overwrite_existing);
}
}
} catch (const std::exception& e) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = e.what();
} }
} }
return {};
}); });
} }
for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile); for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile);
threads.emplace_back([&config, &outputDir, &buildCancelled, &buildError]() { jobs.Add(std::format("Copying files for {}", config.name), [&config, &outputDir]() -> std::string {
Progress::Task task(std::format("Copying files for {}", config.name)); for (const fs::path& additionalFile : config.files) {
if (buildCancelled.load(std::memory_order_relaxed)) return; fs::path destination = outputDir / additionalFile.filename();
try { if (fs::is_directory(additionalFile)) {
for (const fs::path& additionalFile : config.files) { for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) {
fs::path destination = outputDir / additionalFile.filename(); const fs::path& sourcePath = entry.path();
if (fs::is_directory(additionalFile)) { fs::path relativePath = fs::relative(sourcePath, additionalFile);
for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) { fs::path destPath = destination / relativePath;
const fs::path& sourcePath = entry.path(); if (entry.is_directory()) {
fs::path relativePath = fs::relative(sourcePath, additionalFile); if (!fs::exists(destPath)) fs::create_directories(destPath);
fs::path destPath = destination / relativePath; } else if (entry.is_regular_file()) {
if (entry.is_directory()) { fs::create_directories(destPath.parent_path());
if (!fs::exists(destPath)) fs::create_directories(destPath); if (!fs::exists(destPath)) {
} else if (entry.is_regular_file()) { fs::copy_file(sourcePath, destPath);
fs::create_directories(destPath.parent_path()); } else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) {
if (!fs::exists(destPath)) { fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing);
fs::copy_file(sourcePath, destPath);
} else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) {
fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing);
}
} }
} }
} else { }
if (!fs::exists(destination)) { } else {
fs::copy_file(additionalFile, destination); if (!fs::exists(destination)) {
} else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) { fs::copy_file(additionalFile, destination);
fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing); } else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) {
} fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing);
} }
} }
} catch(std::exception& e) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = e.what();
}
} }
return {};
}); });
std::vector<ExternalBuildResult> externalResults(config.externalDependencies.size()); std::vector<ExternalBuildResult> externalResults(config.externalDependencies.size());
@ -1054,7 +1043,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
externalThreads.emplace_back([&, i]() { externalThreads.emplace_back([&, i]() {
const ExternalDependency& dep = config.externalDependencies[i]; const ExternalDependency& dep = config.externalDependencies[i];
Progress::Task task(std::format("Building external dep {}", dep.name)); Progress::Task task(std::format("Building external dep {}", dep.name));
if (buildCancelled.load(std::memory_order_relaxed)) return; if (jobs.Failed()) return;
std::string error; std::string error;
try { try {
// Every configuration of the pass that declares this // Every configuration of the pass that declares this
@ -1072,11 +1061,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} catch (const std::exception& e) { } catch (const std::exception& e) {
error = std::format("external dep {} threw: {}", dep.name, e.what()); error = std::format("external dep {} threw: {}", dep.name, e.what());
} }
if (error.empty()) return; if (!error.empty()) jobs.Fail(std::move(error));
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(error);
}
}); });
} }
@ -1089,8 +1074,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
std::string stdPcmResult; std::string stdPcmResult;
{ {
Progress::Task task(std::format("Building std PCM ({}-{})", config.target, config.march)); Progress::Task task(std::format("Building std PCM ({}-{})", config.target, config.march));
// The shader and external threads are running: an exception leaving // The external threads are running: an exception leaving here would
// here would destroy them joinable, which terminates the process. // destroy them joinable, which terminates the process.
try { try {
stdPcmResult = BuildStdPcm(config, stdPcmDir/"std.pcm"); stdPcmResult = BuildStdPcm(config, stdPcmDir/"std.pcm");
} catch (const std::exception& e) { } catch (const std::exception& e) {
@ -1098,9 +1083,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} }
} }
if(!stdPcmResult.empty()) { if(!stdPcmResult.empty()) {
buildCancelled.store(true); jobs.Fail(stdPcmResult);
for(std::thread& thread : threads) thread.join();
for(std::thread& thread : externalThreads) thread.join(); for(std::thread& thread : externalThreads) thread.join();
jobs.Wait();
return {stdPcmResult, false, {}}; return {stdPcmResult, false, {}};
} }
@ -1136,7 +1121,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
for(Configuration* dep : config.dependencies) { for(Configuration* dep : config.dependencies) {
depThreads.emplace_back([&, dep](){ depThreads.emplace_back([&, dep](){
try { try {
if (buildCancelled.load(std::memory_order_relaxed)) return; if (jobs.Failed()) return;
const std::shared_future<BuildResult> built = OncePerPass(depResults, depMutex, dep->PcmDir(), [&] { return Build(*dep, depResults, depMutex); }); const std::shared_future<BuildResult> built = OncePerPass(depResults, depMutex, dep->PcmDir(), [&] { return Build(*dep, depResults, depMutex); });
const BuildResult& result = built.get(); const BuildResult& result = built.get();
@ -1146,20 +1131,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
for (const std::string& f : result.publicCompileFlags) publicFlagSet.insert(f); for (const std::string& f : result.publicCompileFlags) publicFlagSet.insert(f);
for (const std::string& dir : result.runPaths) runPathSet.insert(dir); for (const std::string& dir : result.runPaths) runPathSet.insert(dir);
fileMutex.unlock(); fileMutex.unlock();
if (!result.result.empty()) { if (!result.result.empty()) jobs.Fail(result.result);
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = result.result;
}
}
if (result.repack) { if (result.repack) {
repack = true; repack = true;
} }
} catch (const std::exception& e) { } catch (const std::exception& e) {
bool expected = false; jobs.Fail(std::format("dep build for {} threw: {}", dep->path.string(), e.what()));
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::format("dep build for {} threw: {}", dep->path.string(), e.what());
}
} }
}); });
} }
@ -1196,17 +1173,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
// depfile the compile below writes is the whole record of what this // depfile the compile below writes is the whole record of what this
// object was built from beyond the .c itself. // object was built from beyond the .c itself.
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) {
threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled, &config, &includeFlags, &defineFlags, &userFlags, &cArchFlags, &ltoCompileFlags]() { jobs.Add(std::format("Compiling {}.c", cFile.filename().string()), [command = std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())] {
Progress::Task task(std::format("Compiling {}.c", cFile.filename().string())); return RunBuildCommand(command);
if (buildCancelled.load(std::memory_order_relaxed)) return;
std::string result = RunBuildCommand(std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string()));
if (result.empty()) return;
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}); });
} }
} }
@ -1225,23 +1193,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) {
const Toolchain& toolchain = GetToolchain(); const Toolchain& toolchain = GetToolchain();
if (toolchain.nvcc.empty()) { if (toolchain.nvcc.empty()) {
bool expected = false; jobs.Fail(std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError));
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::format("cannot compile {}.cu: {}", cFile.filename().string(), toolchain.nvccError);
}
break; break;
} }
threads.emplace_back([&cFile, &buildError, &buildCancelled, &config, &toolchain, srcPath, objPath]() { jobs.Add(std::format("Compiling {}.cu", cFile.filename().string()), [command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] {
Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string())); return RunBuildCommand(command);
if (buildCancelled.load(std::memory_order_relaxed)) return;
std::string result = RunBuildCommand(std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch)));
if (result.empty()) return;
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
}); });
} }
} }
@ -1253,9 +1209,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
thread.join(); thread.join();
} }
if(buildCancelled.load()) { if (jobs.Failed()) {
for(std::thread& thread : threads) thread.join(); return {jobs.Wait(), false, {}};
return {buildError, false, {}};
} }
// Ship runtime artifacts from transitive deps' bin dirs alongside the // Ship runtime artifacts from transitive deps' bin dirs alongside the
@ -1334,7 +1289,8 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
}; };
for (Configuration* dep : config.dependencies) forwardDepArtifacts(dep); for (Configuration* dep : config.dependencies) forwardDepArtifacts(dep);
} catch (const fs::filesystem_error& e) { } catch (const fs::filesystem_error& e) {
for(std::thread& thread : threads) thread.join(); jobs.Fail(e.what());
jobs.Wait();
return {e.what(), false, {}}; return {e.what(), false, {}};
} }
} }
@ -1389,15 +1345,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
if (ext.latestArtifact > externalFloor) externalFloor = ext.latestArtifact; if (ext.latestArtifact > externalFloor) externalFloor = ext.latestArtifact;
} }
// Check every interface before compiling any of them. Module::Compile waits // Check every interface before scheduling any of them. Schedule() puts a
// on the `compiled` flag of each sibling module it imports, and that flag is // unit after the stale units it imports and reads their needsRecompiling
// set either by a Compile that runs or by the Check that decides none is // for that, which a unit's own Check need not have set: a partition's
// needed — so a Check still pending while another module's thread is already // returns at the first stale import it finds.
// waiting would block on a flag nothing goes on to raise.
std::vector<Module*> staleInterfaces;
for(std::unique_ptr<Module>& interface : config.interfaces) { for(std::unique_ptr<Module>& interface : config.interfaces) {
if(interface->Check(pcmDir, externalFloor)) { if(interface->Check(pcmDir, externalFloor)) {
staleInterfaces.push_back(interface.get());
buildResult.repack = true; buildResult.repack = true;
} }
files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string()); files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string());
@ -1406,45 +1359,24 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map<fs::path, s
} }
} }
for(Module* mod : staleInterfaces) { // Every interface, and with each its partitions, not only the stale
threads.emplace_back([mod, &command, &pcmDir, &buildDir, &buildCancelled, &buildError]() { // ones: a unit whose BMI is up to date can still be without the object
Progress::Task task(std::format("Compiling interface {}", mod->path.filename().string())); // made from it, which Schedule() then adds alone. No repack for that
try { // here: the link below runs again for an object newer than its output.
mod->Compile(command, pcmDir, buildDir, buildCancelled, buildError); for(std::unique_ptr<Module>& interface : config.interfaces) {
} catch (const std::exception& e) { interface->Schedule(jobs, command, pcmDir, buildDir);
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::format("Module::Compile threw: {}", e.what());
}
}
});
} }
for(Implementation& implementation : config.implementations) { for(Implementation& implementation : config.implementations) {
if(implementation.Check(buildDir, pcmDir, externalFloor)) { if(implementation.Check(buildDir, pcmDir, externalFloor)) {
buildResult.repack = true; buildResult.repack = true;
Implementation* impl = &implementation; implementation.Schedule(jobs, command, pcmDir, buildDir);
threads.emplace_back([impl, &command, &buildDir, &buildCancelled, &buildError]() {
Progress::Task task(std::format("Compiling {}.cpp", impl->path.filename().string()));
try {
impl->Compile(command, buildDir, buildCancelled, buildError);
} catch (const std::exception& e) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::format("Implementation::Compile threw: {}", e.what());
}
}
});
} }
files += std::format(" {}/{}_impl.o", buildDir.string(), implementation.path.filename().string()); files += std::format(" {}/{}_impl.o", buildDir.string(), implementation.path.filename().string());
} }
for(std::thread& thread : threads) { if (std::string failed = jobs.Wait(); !failed.empty()) {
thread.join(); return {std::move(failed), false, {}};
}
if(buildCancelled.load()) {
return {buildError, false, {}};
} }
std::string linkExtras; std::string linkExtras;
@ -2228,6 +2160,13 @@ object, and invokes its CrafterBuildProject() to obtain a Configuration that
drives the build. Outputs land at bin/<name>-<target>-<march>/, intermediates drives the build. Outputs land at bin/<name>-<target>-<march>/, intermediates
at build/<name>-<target>-<march>/. at build/<name>-<target>-<march>/.
A build runs at most as many of its steps at once as the machine has hardware
threads: the compiles of its sources, its shaders and assets, and its links
and archives, counted together for the project and the dependencies it is
built on. An external dependency's CMake build is not among them, nor are the
tests `test` runs. A step counts as one whatever threads it starts for itself,
as a link and the compression of an asset do.
Build options: Build options:
-r Run the produced executable after a successful build: -r Run the produced executable after a successful build:
one for the host in its own directory, a wasm32 one one for the host in its own directory, a wasm32 one
@ -2244,7 +2183,9 @@ Build options:
Test options (after the `test` subcommand): Test options (after the `test` subcommand):
--list Enumerate matching tests without running them. --list Enumerate matching tests without running them.
--jobs=<N> Parallel job count (default: hardware_concurrency). --jobs=<N> Tests built and run at once (default: one per
hardware thread). The steps of their builds share
the one limit a build has.
--timeout=<seconds> Per-test timeout override. --timeout=<seconds> Per-test timeout override.
--runner=<spec> Override the test runner for this run. Specs: --runner=<spec> Override the test runner for this run. Specs:
local local

View file

@ -5,6 +5,7 @@ module Crafter.Build:Implementation_impl;
import std; import std;
import :Implementation; import :Implementation;
import :Interface; import :Interface;
import :Jobs;
import :Platform; import :Platform;
namespace fs = std::filesystem; namespace fs = std::filesystem;
@ -35,33 +36,22 @@ namespace Crafter {
} }
return false; return false;
} }
void Implementation::Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const { void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const {
std::vector<JobGroup::Job> after;
for(ModulePartition* dependency : partitionDependencies) { for(ModulePartition* dependency : partitionDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false);
}
} }
for(Module* dependency : moduleDependencies) { for(Module* dependency : moduleDependencies) {
if(!dependency->compiled.load()) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
dependency->compiled.wait(false);
}
} }
if (buildCancelled.load(std::memory_order_relaxed)) {
return;
}
// -MD leaves <name>_impl.o.d beside the object for Check to read, and // -MD leaves <name>_impl.o.d beside the object for Check to read, and
// -fmodule-file-deps puts the BMIs the unit imported in it with the // -fmodule-file-deps puts the BMIs the unit imported in it with the
// headers. The driver adds that for --precompile only, so a std // headers. The driver adds that for --precompile only, so a std
// module rebuilt in place, for a mingw-w64 or libc++ update under // module rebuilt in place, for a mingw-w64 or libc++ update under
// the same compiler, left the objects importing it as they were, and // the same compiler, left the objects importing it as they were, and
// the next build only relinked them. // the next build only relinked them.
std::string result = RunBuildCommand(std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())); jobs.Add(std::format("Compiling {}.cpp", path.filename().string()), [command = std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -fmodule-file-deps -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())] {
return RunBuildCommand(command);
bool expected = false; }, after);
if(!result.empty() && buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
}
} }
} }

View file

@ -4,11 +4,55 @@
module Crafter.Build:Interface_impl; module Crafter.Build:Interface_impl;
import std; import std;
import :Interface; import :Interface;
import :Jobs;
import :Platform; import :Platform;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace {
// The job that makes an interface unit's object from its BMI, once the
// jobs in `after` have finished. The command is put together here, as in
// the functions below, so the job owns the one it runs.
void AddObjectJob(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
jobs.Add(std::format("Compiling {}.cppm", path.filename().string()), [command = std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())] {
return Crafter::RunBuildCommand(command);
}, after);
}
// The two compiler runs of a stale interface unit, as jobs of `jobs`: its
// BMI once the jobs in `after` have finished, then its object from that
// BMI. Returns the first, the one the units importing this one come
// after: the object is the link's alone to wait for.
Crafter::JobGroup::Job AddInterfaceJobs(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span<const Crafter::JobGroup::Job> after) {
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
const Crafter::JobGroup::Job precompile = jobs.Add(std::format("Precompiling {}.cppm", path.filename().string()), [command = std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())] {
return Crafter::RunBuildCommand(command);
}, after);
const std::array<Crafter::JobGroup::Job, 1> precompiled = {precompile};
AddObjectJob(jobs, clang, path, pcmDir, buildDir, precompiled);
return precompile;
}
// For a unit whose BMI is up to date: the object job alone, when the
// object is missing or older than the BMI it is made from. The two are
// written by two commands, and a build can end between them: by an error
// elsewhere, which keeps the second from starting, by the second failing,
// or by being interrupted. An object written in the same tick of the
// file system's clock as its BMI is taken to be the later of the two,
// which it is whenever the command that writes it ran.
void AddObjectJobIfStale(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir) {
std::error_code ec;
const fs::file_time_type pcmTime = fs::last_write_time(std::format("{}.pcm", (pcmDir/path.filename()).string()), ec);
// No BMI to make it from; Check does not call such a unit up to date.
if (ec) return;
const fs::file_time_type objectTime = fs::last_write_time(std::format("{}.o", (buildDir/path.filename()).string()), ec);
if (!ec && objectTime >= pcmTime) return;
AddObjectJob(jobs, clang, path, pcmDir, buildDir, {});
}
}
namespace Crafter { namespace Crafter {
ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
if(!checked) { if(!checked) {
@ -44,11 +88,6 @@ namespace Crafter {
} }
} }
needsRecompiling = false; needsRecompiling = false;
compiled.store(true);
// Nothing waits on `compiled` until the compile threads start,
// which is after every Check has run — but notify anyway so the
// flag is never left set without a wake-up behind it.
compiled.notify_all();
return false; return false;
} else { } else {
needsRecompiling = true; needsRecompiling = true;
@ -59,52 +98,25 @@ namespace Crafter {
} }
} }
void ModulePartition::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) { std::optional<JobGroup::Job> ModulePartition::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
for(ModulePartition* dependency : partitionDependencies) { if (scheduled) return precompileJob;
if(!dependency->compiled.load()) { if (needsRecompiling) {
dependency->compiled.wait(false); std::vector<JobGroup::Job> after;
for (ModulePartition* dependency : partitionDependencies) {
if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
} }
} for (Module* dependency : moduleDependencies) {
for(Module* dependency : moduleDependencies) { if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
if(!dependency->compiled.load()) {
dependency->compiled.wait(false);
}
}
if (buildCancelled.load(std::memory_order_relaxed)) {
compiled.store(true);
compiled.notify_all();
return;
}
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
compiled.store(true);
compiled.notify_all();
return;
}
}
compiled.store(true);
compiled.notify_all();
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
} }
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
} else {
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
} }
scheduled = true;
return precompileJob;
} }
Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {}
bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) {
if(!checked) { if(!checked) {
@ -116,7 +128,7 @@ namespace Crafter {
if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) { if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) {
fs::file_time_type pcmTime = fs::last_write_time(pcmPath); fs::file_time_type pcmTime = fs::last_write_time(pcmPath);
// Every partition gets Check()ed even once one is known stale: // Every partition gets Check()ed even once one is known stale:
// Compile() drives partition rebuilds off their own // Schedule() drives partition rebuilds off their own
// needsRecompiling flags, so short-circuiting here would leave // needsRecompiling flags, so short-circuiting here would leave
// the later ones unevaluated and silently unbuilt. // the later ones unevaluated and silently unbuilt.
bool depCheck = false; bool depCheck = false;
@ -149,14 +161,12 @@ namespace Crafter {
return true; return true;
} else { } else {
needsRecompiling = false; needsRecompiling = false;
compiled.store(true);
compiled.notify_all();
return false; return false;
} }
} else { } else {
// Already known stale, but the dependencies still need // Already known stale, but the dependencies still need
// evaluating: an unchecked local module would never get built, // evaluating: Schedule() below reads their needsRecompiling,
// and Compile() below waits on its `compiled` flag. // and an unchecked local module would never get built.
for(std::unique_ptr<ModulePartition>& partition : partitions) { for(std::unique_ptr<ModulePartition>& partition : partitions) {
partition->Check(pcmDir, sourceFloor); partition->Check(pcmDir, sourceFloor);
} }
@ -171,60 +181,29 @@ namespace Crafter {
} }
} }
void Module::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) { std::optional<JobGroup::Job> Module::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) {
// A sibling module in the same Configuration that this interface unit if (scheduled) return precompileJob;
// imports has to have its PCM on disk before we precompile against it. std::vector<JobGroup::Job> after;
// Safe to block here: Build() Checks every interface before it spawns // All of the module's partitions, not the ones the primary interface
// any compile thread, so a dependency that needs no rebuild already has // names: the scanner records no edge for its `import :Part;` lines
// `compiled` set and this returns immediately. // (see GetInterfacesAndImplementations). And of a module that is up
for(Module* dependency : moduleDependencies) { // to date as well: this is where its partitions are scheduled, and
if(!dependency->compiled.load()) { // one of them may be without its object.
dependency->compiled.wait(false); for (const std::unique_ptr<ModulePartition>& partition : partitions) {
} if (const std::optional<JobGroup::Job> job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
} }
if (needsRecompiling) {
std::vector<std::thread> threads; // A sibling module in the same Configuration that this interface
threads.reserve(partitions.size()); // unit imports has to have its PCM on disk before we precompile
for(std::unique_ptr<ModulePartition>& part : partitions) { // against it.
if(part->needsRecompiling) { for (Module* dependency : moduleDependencies) {
threads.emplace_back(&ModulePartition::Compile, part.get(), clang, pcmDir, buildDir, std::ref(buildCancelled), std::ref(buildError)); if (const std::optional<JobGroup::Job> job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job);
}
}
for(std::thread& thread : threads){
thread.join();
}
if (buildCancelled.load(std::memory_order_relaxed)) {
compiled.store(true);
compiled.notify_all();
return;
}
// -MD records every header the preamble pulled in, next to the BMI as
// <name>.pcm.d, so the next Check can see an edit to one of them.
std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
compiled.store(true);
compiled.notify_all();
return;
}
}
compiled.store(true);
compiled.notify_all();
result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string()));
if (!result.empty()) {
bool expected = false;
if (buildCancelled.compare_exchange_strong(expected, true)) {
buildError = std::move(result);
} }
precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after);
} else {
AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir);
} }
scheduled = true;
return precompileJob;
} }
} }

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

View file

@ -18,6 +18,7 @@ import :Toolchain;
import :Clang; import :Clang;
import :Interface; import :Interface;
import :External; import :External;
import :Jobs;
import :Progress; import :Progress;
namespace fs = std::filesystem; namespace fs = std::filesystem;
using namespace Crafter; using namespace Crafter;
@ -25,7 +26,7 @@ using namespace Crafter;
namespace { namespace {
// Exclusive advisory lock over one PCM cache dir (`<cache>/<target>-<march>/`), // Exclusive advisory lock over one PCM cache dir (`<cache>/<target>-<march>/`),
// held for the duration of a (re)build. Concurrent crafter-build invocations — // held for the duration of a (re)build. Concurrent crafter-build invocations —
// and the worker threads inside a single invocation — that share a cache // and the threads of a single invocation that build at once — that share a cache
// serialize their builds through it: the first builder to acquire the lock // serialize their builds through it: the first builder to acquire the lock
// precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else // precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else
// blocks, then re-checks freshness and reuses the finished file instead of // blocks, then re-checks freshness and reuses the finished file instead of
@ -276,34 +277,46 @@ bool Crafter::MatchAny(std::span<const std::string> globs, std::string_view name
return false; return false;
} }
// See the declaration in Crafter.Build-Platform.cppm for why this branches on namespace {
// the exit code rather than on whether the command said anything. // RunBuildCommand's command, run on the thread that calls. See the
// declaration in Crafter.Build-Platform.cppm for why this branches on the
// exit code rather than on whether the command said anything.
std::string RunBuildStep(std::string_view cmd) {
Progress::EchoCommand(cmd);
CommandResult r = RunCommandChecked(cmd);
// A mingw build against a system prefix sees mingw-w64 through a view in
// the cache, and clang names every header by the path it found it at.
r.output = MingwViewToPrefix(std::move(r.output));
if (r.exitCode == 0) {
// Warnings from a step that succeeded. Show them — until now they were
// invisible on an incremental build and fatal on a cold one.
if (!r.output.empty()) Progress::Diagnostic(r.output);
return "";
}
// A compiler killed outright (the OOM killer is the common one) prints
// nothing, so the old "output means failure" rule read it as success and
// let the build carry on with a missing object. Say what happened instead.
if (r.output.empty()) {
return r.crashed
? std::format("terminated by signal {}: {}", r.signal, cmd)
: std::format("exited with code {}: {}", r.exitCode, cmd);
}
if (r.crashed) {
return std::format("{}\nterminated by signal {}", r.output, r.signal);
}
return r.output;
}
}
std::string Crafter::RunBuildCommand(std::string_view cmd) { std::string Crafter::RunBuildCommand(std::string_view cmd) {
Progress::EchoCommand(cmd); // A job is on a worker already and runs the command where it is. A link,
CommandResult r = RunCommandChecked(cmd); // or the precompile of the std module, comes from the thread of a Build()
// A mingw build against a system prefix sees mingw-w64 through a view in // or a LoadProject and waits here for its turn among the jobs.
// the cache, and clang names every header by the path it found it at. std::string result;
r.output = MingwViewToPrefix(std::move(r.output)); JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); });
return result;
if (r.exitCode == 0) {
// Warnings from a step that succeeded. Show them — until now they were
// invisible on an incremental build and fatal on a cold one.
if (!r.output.empty()) Progress::Diagnostic(r.output);
return "";
}
// A compiler killed outright (the OOM killer is the common one) prints
// nothing, so the old "output means failure" rule read it as success and
// let the build carry on with a missing object. Say what happened instead.
if (r.output.empty()) {
return r.crashed
? std::format("terminated by signal {}: {}", r.signal, cmd)
: std::format("exited with code {}: {}", r.exitCode, cmd);
}
if (r.crashed) {
return std::format("{}\nterminated by signal {}", r.output, r.signal);
}
return r.output;
} }
// --- Dependencies of project.cpp itself ------------------------------------- // --- Dependencies of project.cpp itself -------------------------------------
@ -874,7 +887,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) {
// and, when clang finds no gcc directory, an empty entry that would // and, when clang finds no gcc directory, an empty entry that would
// name a manifest in the working directory. A toolchain that isn't // name a manifest in the working directory. A toolchain that isn't
// there is a build error, not an exception: Build() runs this with // there is a build error, not an exception: Build() runs this with
// its worker threads started. // the threads of its external dependencies started.
const Toolchain& tc = GetToolchain(); const Toolchain& tc = GetToolchain();
const std::string where = tc.mingwPrefix.empty() const std::string where = tc.mingwPrefix.empty()
? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH") ? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH")
@ -995,11 +1008,12 @@ std::string Crafter::GetBaseCommand(const Configuration& config) {
} }
namespace { namespace {
constexpr std::array<std::string_view, 15> CrafterBuildModules = { constexpr std::array<std::string_view, 16> CrafterBuildModules = {
"Crafter.Build-Toolchain", "Crafter.Build-Toolchain",
"Crafter.Build-Shader", "Crafter.Build-Shader",
"Crafter.Build-Platform", "Crafter.Build-Platform",
"Crafter.Build-Flatpak", "Crafter.Build-Flatpak",
"Crafter.Build-Jobs",
"Crafter.Build-Interface", "Crafter.Build-Interface",
"Crafter.Build-Implementation", "Crafter.Build-Implementation",
"Crafter.Build-External", "Crafter.Build-External",

View file

@ -3,6 +3,7 @@
export module Crafter.Build:Implementation; export module Crafter.Build:Implementation;
import std; import std;
import :Jobs;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Crafter { namespace Crafter {
@ -19,6 +20,9 @@ namespace Crafter {
fs::path path; fs::path path;
Implementation(fs::path&& path); Implementation(fs::path&& path);
bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const; bool Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()) const;
void Compile(const std::string_view clang, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError) const; // Adds the job that compiles this unit to `jobs`, after the BMIs of
// the stale interface units it imports (ModulePartition::Schedule,
// Module::Schedule). For a unit Check found stale.
void Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) const;
}; };
} }

View file

@ -3,6 +3,7 @@
export module Crafter.Build:Interface; export module Crafter.Build:Interface;
import std; import std;
import :Jobs;
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace Crafter { namespace Crafter {
@ -19,14 +20,38 @@ namespace Crafter {
// GetInterfacesAndImplementations still produces a staleness edge. // GetInterfacesAndImplementations still produces a staleness edge.
// Names that never resolve (`std`, module-mapped externals) stay here. // Names that never resolve (`std`, module-mapped externals) stay here.
std::vector<std::string> pendingImports; std::vector<std::string> pendingImports;
std::atomic<bool> compiled; // The state of one Build(), which clears it before it checks: whether
// Check has run, what it found, whether Schedule has added this
// unit's jobs, and the one among them that writes its BMI, which is
// the job the units importing it come after.
bool needsRecompiling = false; bool needsRecompiling = false;
bool checked = false; bool checked = false;
bool scheduled = false;
std::optional<JobGroup::Job> precompileJob;
std::string name; std::string name;
fs::path path; fs::path path;
ModulePartition(std::string&& name, fs::path&& path); ModulePartition(std::string&& name, fs::path&& path);
// Whether this unit's BMI has to be written again. The object made
// from the BMI is not Check's to judge: see Schedule.
bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()); bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min());
void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError); // Adds the jobs this unit needs to `jobs`, once however often it is
// called, and returns the one that writes its BMI, if there is one.
//
// A unit Check found stale gets two, one for each run of `clang`: the
// BMI, after the BMIs of the stale units this one imports, which are
// scheduled here as well, and then the object from that BMI, which
// only the link waits for, so that the units importing this one start
// when the first is done.
//
// A unit whose BMI is up to date gets the second job alone when its
// object is missing or older than the BMI. A build that fails or is
// interrupted between the two leaves a unit like that, and by its BMI
// alone every build after it would call the unit built: the link then
// took the object of the source before the edit, or found none.
//
// Every unit this one imports must have been checked: Build() checks
// all of a configuration's interfaces before it schedules any.
std::optional<JobGroup::Job> Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir);
}; };
export class Module { export class Module {
@ -34,20 +59,27 @@ namespace Crafter {
// A primary module interface unit imports things too — `import Base;` // A primary module interface unit imports things too — `import Base;`
// in `export module Widget;` is as much a layout dependency as the // in `export module Widget;` is as much a layout dependency as the
// same line in a partition. Recorded on the same three vectors, with // same line in a partition. Recorded on the same three vectors, with
// the same meanings, so Check() can see through them and Compile() // the same meanings, so Check() can see through them and Schedule()
// can order itself behind a sibling module in the same Configuration // can order itself behind a sibling module in the same Configuration
// (issue #26). // (issue #26).
std::vector<Module*> moduleDependencies; std::vector<Module*> moduleDependencies;
std::vector<std::pair<Module*, fs::path>> externalModuleDependencies; std::vector<std::pair<Module*, fs::path>> externalModuleDependencies;
std::vector<std::string> pendingImports; std::vector<std::string> pendingImports;
std::atomic<bool> compiled; // As in ModulePartition.
bool needsRecompiling = false; bool needsRecompiling = false;
bool checked = false; bool checked = false;
bool scheduled = false;
std::optional<JobGroup::Job> precompileJob;
std::vector<std::unique_ptr<ModulePartition>> partitions; std::vector<std::unique_ptr<ModulePartition>> partitions;
std::string name; std::string name;
fs::path path; fs::path path;
Module(std::string&& name, fs::path&& path); Module(std::string&& name, fs::path&& path);
bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min()); bool Check(const fs::path& pcmDir, fs::file_time_type sourceFloor = fs::file_time_type::min());
void Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic<bool>& buildCancelled, std::string& buildError); // As ModulePartition::Schedule, for the primary interface, and
// schedules every partition of the module with it. The primary
// interface comes after every stale partition of the module,
// whichever of them it imports, and after the stale sibling modules
// it imports.
std::optional<JobGroup::Job> Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir);
}; };
} }

View file

@ -0,0 +1,129 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Build:Jobs;
import std;
export namespace Crafter {
// The threads build steps run on: a fixed number of workers taking jobs
// from one queue, so that no more steps run at once than there are
// workers, whichever builds they belong to. Process() is the pool every
// build in this process shares, with a worker per hardware thread.
//
// A job is one step of a build: one compiler, linker or archiver run, one
// shader or asset compiled in process. The pool bounds the steps that run
// at once, not the threads a step starts for itself, as lld does for a
// link and the compressor of Crafter.Asset for an asset.
//
// A job never waits for another job. Whatever waits does so on a
// thread that is not a worker: a Build() for the builds of its
// dependencies, a step for the steps it comes after (JobGroup holds it
// back instead). A worker that waited for a job still in the queue would
// keep from it the very thread it needs, and with every worker waiting
// like that nothing would run again.
//
// Before this, Build() started a thread for every stale shader, asset
// to compress, C, CUDA and C++ unit, and nothing bounded how many of
// them ran at once.
class JobPool {
public:
// At most `workers` jobs at once, at least one. The threads are
// started as jobs need them: a build with two stale files starts two.
explicit JobPool(std::uint32_t workers);
// Runs what is still queued, then joins the workers. Nothing may be
// handing it jobs any more: every group on it is gone by then.
~JobPool();
JobPool(const JobPool&) = delete;
JobPool& operator=(const JobPool&) = delete;
// The pool of this process: one worker per hardware thread
// (std::thread::hardware_concurrency), and one where that is not
// known. Never destroyed, so that its workers are not joined while
// the statics the last job may still be using are being destroyed.
static JobPool& Process();
std::uint32_t Workers() const;
// Runs `work` on a worker and returns when it has finished; what it
// throws is thrown here. For a step that stands by itself, as
// RunBuildCommand uses it for a link. Called on a worker of this
// pool it runs `work` there and then, since that thread is the one
// the step would have occupied.
void Run(const std::function<void()>& work);
private:
friend class JobGroup;
// Queues `job`, which must not throw. Throws only when the pool has
// no thread and cannot start one, and then `job` is not queued.
void Submit(std::function<void()> job);
void Work();
const std::uint32_t limit;
std::mutex mutex;
std::condition_variable wake;
std::deque<std::function<void()>> queue;
std::vector<std::thread> threads;
// Workers waiting for a job. A job queued while one waits is its to
// take, so a thread is only started for a job beyond those.
std::uint32_t idle = 0;
bool stopping = false;
};
// The jobs of one piece of work, such as the build of a configuration,
// on the workers of a pool. A job starts once every job it was added
// after has finished, so the order steps need (a unit after the BMIs it
// imports) costs no thread while it is waited for.
//
// The first job to fail fails the group: no job of it starts after that,
// the ones already running finish, and Wait() returns that first error.
// Fail() does the same for work done outside the jobs, so one group
// holds the outcome of everything a build runs at once.
class JobGroup {
public:
using Job = std::size_t;
// Throws std::logic_error on a worker of `pool`: a job that waited
// for jobs of its own would occupy a worker they need (see JobPool).
explicit JobGroup(JobPool& pool = JobPool::Process());
// Keeps what has not started from starting and waits for what is
// running, so a job never outlives what it was given by reference,
// whichever way the scope that made the group is left.
~JobGroup();
JobGroup(const JobGroup&) = delete;
JobGroup& operator=(const JobGroup&) = delete;
// Adds a job, counted as a Progress::Task under `label` from now
// until it has finished or been skipped. It starts once every job in
// `after` has finished, at once when there is none; `after` names
// jobs of this group, so a job can only come after ones added before
// it and no two can wait for each other. `work` returns what went
// wrong, empty when nothing did; an exception it throws is its error
// too. It runs on a worker: it must not wait for other jobs, and it
// must own what it uses or use only what outlives the group.
Job Add(std::string label, std::function<std::string()> work, std::span<const Job> after = {});
// Fails the group with `error`, as a job returning it would. Without
// effect on a group that has already failed.
void Fail(std::string error);
bool Failed() const;
// Returns once every job added so far has finished or been skipped:
// the first error, empty when there was none.
std::string Wait();
private:
struct Node;
void Start(Node& node);
void Execute(Node& node);
JobPool& pool;
mutable std::mutex mutex;
std::condition_variable settled;
// Owned through pointers: a job on a worker holds on to its node
// while Add() grows the vector.
std::vector<std::unique_ptr<Node>> nodes;
std::size_t unfinished = 0;
bool failed = false;
std::string error;
};
}

View file

@ -42,6 +42,11 @@ namespace Crafter {
// Returns an empty string on success (any warnings go to the user via // Returns an empty string on success (any warnings go to the user via
// Progress::Diagnostic), otherwise the compiler's diagnostics. Callers // Progress::Diagnostic), otherwise the compiler's diagnostics. Callers
// therefore keep the `if (!result.empty())` shape they already had. // therefore keep the `if (!result.empty())` shape they already had.
//
// The command runs on a worker of JobPool::Process(), so no more of these
// steps run at once than that pool has workers: called on one of its
// workers it runs there, called from any other thread it waits for one.
// A step that runs a compiler any other way is not counted.
std::string RunBuildCommand(std::string_view command); std::string RunBuildCommand(std::string_view command);
export CommandResult RunCommandWithTimeout(std::string_view command, std::chrono::seconds timeout); export CommandResult RunCommandWithTimeout(std::string_view command, std::chrono::seconds timeout);
// Runs `command` through sh with this process's own stdin, stdout and // Runs `command` through sh with this process's own stdin, stdout and

View file

@ -12,8 +12,10 @@ export namespace Crafter::Progress {
// RAII work-unit marker. Construction inflates the running total; destruction // RAII work-unit marker. Construction inflates the running total; destruction
// increments completed and (on Default + TTY) redraws the status line. Move // increments completed and (on Default + TTY) redraws the status line. Move
// semantics are disabled — keep these as plain stack locals inside the worker // semantics are disabled — keep these as plain stack locals around the work
// lambda so the destructor fires when that thread's work ends. // they count, so the destructor fires when it ends. A job of a JobGroup
// gets one from Add(), made when the job is queued, which is what puts
// work that has not started yet in the total.
class Task { class Task {
public: public:
explicit Task(std::string label); explicit Task(std::string label);

View file

@ -57,6 +57,10 @@ export namespace Crafter {
struct RunTestsOptions { struct RunTestsOptions {
std::vector<std::string> globs; std::vector<std::string> globs;
// Tests built and run at once, from --jobs=; 0 is one per hardware
// thread. It counts tests, not build steps: the steps of their builds
// run on JobPool::Process() under that pool's own limit, and a test
// that is running is not one of them.
std::int32_t jobs = 0; std::int32_t jobs = 0;
std::optional<std::chrono::seconds> timeoutOverride; std::optional<std::chrono::seconds> timeoutOverride;
bool listOnly = false; bool listOnly = false;

View file

@ -6,6 +6,7 @@ export import :Toolchain;
export import :Flatpak; export import :Flatpak;
export import :Clang; export import :Clang;
export import :Platform; export import :Platform;
export import :Jobs;
export import :Implementation; export import :Implementation;
export import :Shader; export import :Shader;
export import :External; export import :External;

View file

@ -173,12 +173,13 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
// it reaches clang, which must still see a string literal. // it reaches clang, which must still see a string literal.
CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)}); CrafterBuildLib->defines.push_back({"CRAFTER_BUILD_VERSION", std::format("\\\"{}\\\"", version)});
{ {
std::array<fs::path, 15> interfaces = { std::array<fs::path, 16> interfaces = {
"interfaces/Crafter.Build", "interfaces/Crafter.Build",
"interfaces/Crafter.Build-Toolchain", "interfaces/Crafter.Build-Toolchain",
"interfaces/Crafter.Build-Shader", "interfaces/Crafter.Build-Shader",
"interfaces/Crafter.Build-Platform", "interfaces/Crafter.Build-Platform",
"interfaces/Crafter.Build-Flatpak", "interfaces/Crafter.Build-Flatpak",
"interfaces/Crafter.Build-Jobs",
"interfaces/Crafter.Build-Interface", "interfaces/Crafter.Build-Interface",
"interfaces/Crafter.Build-Implementation", "interfaces/Crafter.Build-Implementation",
"interfaces/Crafter.Build-External", "interfaces/Crafter.Build-External",
@ -190,11 +191,12 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
"interfaces/Crafter.Build-Progress", "interfaces/Crafter.Build-Progress",
"interfaces/Crafter.Build-Asset", "interfaces/Crafter.Build-Asset",
}; };
std::array<fs::path, 14> implementations = { std::array<fs::path, 15> implementations = {
"implementations/Crafter.Build-Toolchain", "implementations/Crafter.Build-Toolchain",
"implementations/Crafter.Build-Shader", "implementations/Crafter.Build-Shader",
"implementations/Crafter.Build-Platform", "implementations/Crafter.Build-Platform",
"implementations/Crafter.Build-Flatpak", "implementations/Crafter.Build-Flatpak",
"implementations/Crafter.Build-Jobs",
"implementations/Crafter.Build-Interface", "implementations/Crafter.Build-Interface",
"implementations/Crafter.Build-Implementation", "implementations/Crafter.Build-Implementation",
"implementations/Crafter.Build-External", "implementations/Crafter.Build-External",

View file

@ -5,6 +5,8 @@ module DepMod;
// Implementation unit of the DepMod interface. Because it declares // Implementation unit of the DepMod interface. Because it declares
// `module DepMod;` it gains an intra-config module dependency on the DepMod // `module DepMod;` it gains an intra-config module dependency on the DepMod
// interface, so its compile waits on DepMod's `compiled` flag — the exact // interface, so its compile job comes after the job that writes DepMod's BMI
// flag a stale recursive reset used to clobber (issue #16). // (Implementation::Schedule), which reads DepMod's per-build state: what a
// recursive reset would clear. Its compile used to wait on DepMod's
// `compiled` flag, the flag such a reset clobbered (issue #16).
int dep_value() { return 21; } int dep_value() { return 21; }

View file

@ -8,26 +8,33 @@ using namespace Crafter;
// Regression for the concurrent dependency-reset deadlock (issue #16). // Regression for the concurrent dependency-reset deadlock (issue #16).
// //
// Build() resets each Module/ModulePartition's per-build `compiled` /`checked` // Build() resets each Module/ModulePartition's per-build state (`checked`,
// flags so a reused Configuration re-evaluates mtimes. That reset MUST stay // `scheduled` and the job that precompiles the unit) so a reused Configuration
// scoped to the configuration being built. It used to recurse into // re-evaluates mtimes. That reset MUST stay scoped to the configuration being
// cfg.dependencies — but dependency Configurations are shared across the build // built. It used to recurse into cfg.dependencies — but dependency
// DAG and each is compiled concurrently by its own Build() call. A parent's // Configurations are shared across the build DAG and each is built
// recursive reset could therefore clear a dependency's module `compiled` flag // concurrently by its own Build() call. Every unit then had a thread of its
// own and a `compiled` flag that the units importing it waited on, and a
// parent's recursive reset could clear a dependency's module `compiled` flag
// *after* that dependency's module-compile thread had set it true and exited, // *after* that dependency's module-compile thread had set it true and exited,
// but before an intra-config waiter (its impl / a dependent partition) ran // but before an intra-config waiter (its impl / a dependent partition) ran
// `compiled.wait(false)`. The waiter then blocked forever on a flag nothing // `compiled.wait(false)`. The waiter then blocked forever on a flag nothing
// re-signalled: the build froze mid-compile, idle, with no compiler process // re-signalled: the build froze mid-compile, idle, with no compiler process
// alive. // alive.
// //
// Units are jobs now and wait on no flag, but the state is still the building
// configuration's alone: cleared from outside between two Schedule() calls of
// its own build, a unit is scheduled twice and compiled twice at once.
//
// This test pins the invariant deterministically, without depending on thread // This test pins the invariant deterministically, without depending on thread
// timing: build a static-lib dependency fully (its module ends up compiled), // timing: build a static-lib dependency fully (its module ends up checked and
// then build a consumer that depends on it while the dependency is already // scheduled), then build a consumer that depends on it while the dependency is
// cached in depResults (so it is NOT rebuilt). Before the fix, the consumer's // already cached in depResults (so it is NOT rebuilt). A consumer that reset
// recursive reset flipped the dependency's module `compiled` flag back to false // its dependencies would flip the dependency's module `checked` and
// and, because the dependency never rebuilds, it stayed false. After the fix // `scheduled` flags back to false and, because the dependency never rebuilds,
// the consumer resets only its own modules, so the dependency's flag is left // they would stay false. The consumer resets only its own modules, so the
// intact. We assert it is still set once the consumer build completes. // dependency's flags are left intact. We assert both are still set once the
// consumer build completes.
int main() { int main() {
fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture"; fs::path fixtureRoot = fs::current_path() / "tests" / "ConcurrentDependencyReset" / "fixture";
@ -64,8 +71,8 @@ int main() {
std::println(std::cerr, "dependency build failed: {}", r.result); std::println(std::cerr, "dependency build failed: {}", r.result);
return 1; return 1;
} }
if (!dep.interfaces[0]->compiled.load()) { if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
std::println(std::cerr, "dependency module not marked compiled after its own build"); std::println(std::cerr, "dependency module not marked checked and scheduled after its own build");
return 1; return 1;
} }
// Seed a consumer-facing cache so the consumer reuses this build instead // Seed a consumer-facing cache so the consumer reuses this build instead
@ -98,10 +105,9 @@ int main() {
} }
// The core regression assertion: building the consumer must not have // The core regression assertion: building the consumer must not have
// reset the (cached, never-rebuilt) dependency's module flag. Before the // reset the (cached, never-rebuilt) dependency's module state.
// fix this was false and an intra-config waiter would have deadlocked. if (!dep.interfaces[0]->checked || !dep.interfaces[0]->scheduled) {
if (!dep.interfaces[0]->compiled.load()) { std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module state " "(issue #16 regression): done while that dependency is building, " "this compiles its units twice at once");
std::println(std::cerr, "FAIL: consumer build reset a cached dependency's module 'compiled' " "flag (issue #16 regression) — this is the state that deadlocks a " "concurrent build");
return 1; return 1;
} }

View file

@ -17,12 +17,12 @@ using namespace Crafter;
// layouts with no diagnostic. That is the reported failure: rebuild the // layouts with no diagnostic. That is the reported failure: rebuild the
// dependency, relink the test, crash somewhere unrelated. // dependency, relink the test, crash somewhere unrelated.
// //
// * `Module::Compile` waited on nothing. Two modules in one Configuration // * `Module::Compile`, as it was then, waited on nothing. Two modules in
// compile on concurrent threads, so importing a sibling was a coin flip // one Configuration compiled on concurrent threads, so importing a sibling
// between working and "module 'Base' not found". // was a coin flip between working and "module 'Base' not found".
// //
// Partitions never had either problem — they carry the same three vectors and // Partitions never had either problem — they carry the same three vectors and
// Check/Compile honour them — which is why the gap only shows up on a module // Check/Schedule honour them — which is why the gap only shows up on a module
// whose interface is one flat unit. tests/IncrementalInterfaceChange covers the // whose interface is one flat unit. tests/IncrementalInterfaceChange covers the
// neighbouring consumer-side edge (issue #27). // neighbouring consumer-side edge (issue #27).