Crafter.Build/tests/JobLimit/main.cpp
Jorijn van der Graaf 3c8f4ddb54
fix(build): read what a source declares and imports with clang-scan-deps
GetInterfacesAndImplementations found the module declarations and the
imports of a configuration's sources by searching their text with
regular expressions, after deleting the comments that fit on one line.
The expressions skipped neither string literals nor comments that span
lines, knew nothing of the preprocessor, and wanted one space after
`import` and none before its semicolon (#45). An implementation source
that held "export module std;" in a string literal was taken for a unit
of a module std, and listing it threw "Module std not found not found".
An import in a comment that spans lines or under #if 0 was followed.
`import  X;` and `import X ;` were missed, so their unit had no edge to
the module it imports and could be compiled before that module's BMI was
written.

What a .cppm or .cpp declares and imports now comes from clang-scan-deps
-format=p1689, which preprocesses the source with the configuration's
C++ compile command, the one Build() compiles every unit of it with:
strings, comments, spacing, macros and #if come out as they do for the
compiler. GetInterfacesAndImplementations only lists the sources, in the
new interfaceSources and implementationSources. Build() reads them
(ReadSources) once the configuration's dependencies and external
dependencies are built: the command takes their include paths, and a
source may include headers of an external dependency, which are not
there before it is fetched. From what it read, Build() makes the
configuration's modules and units, its `interfaces` and
`implementations`, and places each import on a module of the
configuration or of what it is built on, whose own Build() has read its
sources by then. It makes those of its own configuration alone, as the
reset of the units' state did before it.

A build pass builds a directory once, for whichever configuration of it
asks first, and the loader can make two configurations of one directory:
one project loaded along two paths with its args in two orders, which it
keeps apart and VariantId, sorting the args, does not. Only the one that
was built has the modules that build read, so the result of a build now
names the configuration it ran on (BuildResult::built), and a
dependency's modules are looked up through the pass's record of its
directory. 6.4.1 had every configuration's modules from the listing and
took such a graph for one with two builds of a module, which it refused;
it is now built, once, and the units of both sides have their edges.

A scan is kept in the build directory as an object is, in scans/ or, for
a source outside cfg.path, in scans-outside/, as JSON of the command it
was taken with and of what clang-scan-deps wrote, with the dependency
file clang-scan-deps wrote beside it, which lists the source and every
file it included. A build scans a source again unless its scan is newer
than every file that dependency file lists, was taken with the same
command and can be read, so a build with nothing changed runs no
clang-scan-deps. Both files are written beside their places and renamed
into them, as the archive and the list of objects are, for another
crafter-build that may be building the same clone.

A configuration's modules are known only once its build has read its
sources, so the refusals of a module that two configurations of the
graph build (DuplicateModuleError, #41) and of interface units that
import each other (ImportCycleError) now come there: once the
dependencies are built, before any .cppm or .cpp of the configuration is
compiled. They came before the configuration made a directory or built a
dependency. The contributor guide names clang-scan-deps among the
prerequisites and among what :Toolchain resolves, has a test look at the
modules of a configuration only after building it, and has the gotcha
for the new order.

ResolvePendingImports and the pendingImports of the unit classes go.
They placed the imports that a scan at listing time could not, once the
dependencies were wired up, and with the imports placed when the
dependencies are built there is nothing pending. The tests that looked
at a configuration's modules and units before building now look after it
(DependencyLink, ModuleInterface, StaticLib, ConcurrentDependencyReset
and the disabled TransitiveInterfaceChange), IncrementalInterfaceChange
checks the edge that the build of a consumer gives it when its
dependency was assigned after its sources were listed, and ImportCycle
and DuplicateModule check that the refused configuration compiled
nothing of its own. The workarounds for the old scanner are not needed:
MingwSysroot writes its stand-in std module as a plain literal again,
JobLimit writes the declarations of the sources it generates as plain
literals, and Lint's comment on its fixture file no longer gives the
scanner as the reason for it.

The messages of the regex code stay where they still apply. The one for
a source that declares a unit of a module the configuration does not
have loses its doubled "not found", and applies to an implementation
source that declares one, such as an implementation partition
(`module X:P;`). An implementation unit written `module X;` declares no
unit for clang-scan-deps but imports X, and an import needs no module of
the configuration: the compile reports a module no one builds. A .cppm
that declares an implementation partition is built as a partition of its
module, where it was refused as declaring no module.

The Toolchain gains clangScanDeps, resolved as llvm-ar is: in the bin/
of the LLVM prefix, else by name on PATH. The Flatpak has
/app/bin/clang-scan-deps.

Fixes #45
2026-11-27 09:25:53 +01:00

170 lines
8.3 KiB
C++

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