Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
This commit is contained in:
1 parent
3cac890ce9
commit
ab64147f9d
114 files changed
+23777
-1392
No files matched your search
@@ -0,0 +1,542 @@
|
||||
#include <Void/Build/Execution/Scheduler.hpp>
|
||||
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <Void/Build/Platform/FileOps.hpp>
|
||||
#include <Void/Build/Platform/ProcessSupervisor.hpp>
|
||||
#include <Void/Build/Util/Sha256.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Time/Stopwatch.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <format>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
|
||||
namespace Void::Build::Execution {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error make_error(std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument,
|
||||
std::move(msg));
|
||||
}
|
||||
|
||||
std::string compute_effective_action_key(const Graph::ActionNode &action) {
|
||||
// Re-hash declared input file bytes at execution time (including generated upstream outputs!)
|
||||
// so downstream compile/archive/link actions invalidate immediately when an upstream artifact
|
||||
// changes.
|
||||
Util::Sha256Hasher hasher;
|
||||
hasher.update_length_prefixed(action.action_key);
|
||||
for (const auto &in_path : action.declared_inputs) {
|
||||
hasher.update_length_prefixed(in_path.string());
|
||||
if (auto digest = Util::sha256_file_hex(in_path); digest) {
|
||||
hasher.update_length_prefixed(*digest);
|
||||
} else {
|
||||
hasher.update_length_prefixed("<missing>");
|
||||
}
|
||||
}
|
||||
return hasher.finalize_hex();
|
||||
}
|
||||
|
||||
bool verify_discovered_inputs_unchanged(
|
||||
const std::map<std::string, std::string, std::less<>> &discovered_inputs) {
|
||||
for (const auto &[path_str, expected_sha] : discovered_inputs) {
|
||||
auto actual = Util::sha256_file_hex(std::filesystem::path{path_str});
|
||||
if (!actual || *actual != expected_sha) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool verify_outputs_match_record(const Graph::ActionNode &action,
|
||||
const State::ActionSuccessRecord &record) {
|
||||
for (const auto &out_path : action.declared_outputs) {
|
||||
const auto it = record.outputs.find(out_path.string());
|
||||
if (it == record.outputs.end()) {
|
||||
return false;
|
||||
}
|
||||
auto actual = Util::sha256_file_hex(out_path);
|
||||
if (!actual || *actual != it->second.sha256) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool restore_outputs_from_cache(const Graph::ActionNode &action,
|
||||
const State::ActionSuccessRecord &record,
|
||||
const State::StateStore &state) {
|
||||
for (const auto &out_path : action.declared_outputs) {
|
||||
const auto it = record.outputs.find(out_path.string());
|
||||
if (it == record.outputs.end()) {
|
||||
return false;
|
||||
}
|
||||
auto mat = state.materialize_blob(it->second, out_path);
|
||||
if (!mat) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::set<std::string> collect_ancestors(const Graph::BuildGraph &graph, const std::string &id) {
|
||||
std::set<std::string> ancestors;
|
||||
std::queue<std::string> q;
|
||||
const auto idx_it = graph.action_index_by_id.find(id);
|
||||
if (idx_it == graph.action_index_by_id.end()) {
|
||||
return ancestors;
|
||||
}
|
||||
for (const auto &dep : graph.actions[idx_it->second].dependencies) {
|
||||
if (ancestors.insert(dep).second) {
|
||||
q.push(dep);
|
||||
}
|
||||
}
|
||||
while (!q.empty()) {
|
||||
const auto cur = q.front();
|
||||
q.pop();
|
||||
const auto cit = graph.action_index_by_id.find(cur);
|
||||
if (cit == graph.action_index_by_id.end()) {
|
||||
continue;
|
||||
}
|
||||
for (const auto &dep : graph.actions[cit->second].dependencies) {
|
||||
if (ancestors.insert(dep).second) {
|
||||
q.push(dep);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ancestors;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
|
||||
parse_depfile(const std::filesystem::path &depfile_path) {
|
||||
auto text = Void::FileSystem::read_file(depfile_path);
|
||||
if (!text) {
|
||||
return std::unexpected{text.error()};
|
||||
}
|
||||
|
||||
// Remove backslash-newline continuations.
|
||||
std::string unfolded;
|
||||
unfolded.reserve(text->size());
|
||||
for (std::size_t i = 0; i < text->size(); ++i) {
|
||||
if ((*text)[i] == '\\' && i + 1 < text->size() && (*text)[i + 1] == '\n') {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if ((*text)[i] == '\\' && i + 2 < text->size() && (*text)[i + 1] == '\r' &&
|
||||
(*text)[i + 2] == '\n') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
unfolded.push_back((*text)[i]);
|
||||
}
|
||||
|
||||
// Find the first unescaped colon separating target(s) from prerequisites.
|
||||
std::size_t colon = std::string::npos;
|
||||
for (std::size_t i = 0; i < unfolded.size(); ++i) {
|
||||
if (unfolded[i] == '\\' && i + 1 < unfolded.size()) {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (unfolded[i] == ':') {
|
||||
colon = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (colon == std::string::npos) {
|
||||
return std::unexpected{make_error(std::format(
|
||||
"parse_depfile: malformed depfile '{}' (missing ':')", depfile_path.string()))};
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> deps;
|
||||
std::set<std::string> seen;
|
||||
std::size_t pos = colon + 1;
|
||||
while (pos < unfolded.size()) {
|
||||
while (pos < unfolded.size() && (unfolded[pos] == ' ' || unfolded[pos] == '\t' ||
|
||||
unfolded[pos] == '\n' || unfolded[pos] == '\r')) {
|
||||
++pos;
|
||||
}
|
||||
if (pos >= unfolded.size()) {
|
||||
break;
|
||||
}
|
||||
std::string token;
|
||||
while (pos < unfolded.size() && unfolded[pos] != ' ' && unfolded[pos] != '\t' &&
|
||||
unfolded[pos] != '\n' && unfolded[pos] != '\r') {
|
||||
if (unfolded[pos] == '\\' && pos + 1 < unfolded.size()) {
|
||||
const char next = unfolded[pos + 1];
|
||||
if (next == ' ' || next == '#' || next == '\\' || next == ':') {
|
||||
token.push_back(next);
|
||||
pos += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (unfolded[pos] == '$' && pos + 1 < unfolded.size() && unfolded[pos + 1] == '$') {
|
||||
token.push_back('$');
|
||||
pos += 2;
|
||||
continue;
|
||||
}
|
||||
token.push_back(unfolded[pos++]);
|
||||
}
|
||||
if (!token.empty() && seen.insert(token).second) {
|
||||
deps.emplace_back(std::move(token));
|
||||
}
|
||||
}
|
||||
return deps;
|
||||
}
|
||||
|
||||
Void::Result::Result<ExecutionReport, Void::Result::Error>
|
||||
execute_graph(const Graph::BuildGraph &graph, State::StateStore &state,
|
||||
const ExecutionOptions &options, std::stop_token external_stop) {
|
||||
auto selected_indices_res = graph.select_action_closure(options.selected_targets);
|
||||
if (!selected_indices_res) {
|
||||
return std::unexpected{selected_indices_res.error()};
|
||||
}
|
||||
const auto &selected_indices = *selected_indices_res;
|
||||
|
||||
ExecutionReport report;
|
||||
report.total_selected = selected_indices.size();
|
||||
if (selected_indices.empty()) {
|
||||
report.succeeded = true;
|
||||
return report;
|
||||
}
|
||||
|
||||
// Serialize writers to the same profile directory; independent profiles run concurrently.
|
||||
const auto profile_lock_path = graph.profile_build_dir / ".profile.lock";
|
||||
auto profile_lock =
|
||||
Platform::FileLock::acquire(profile_lock_path, Platform::LockMode::Exclusive);
|
||||
if (!profile_lock) {
|
||||
return std::unexpected{profile_lock.error()};
|
||||
}
|
||||
|
||||
auto lease = state.acquire_lease(graph.profile.name);
|
||||
if (!lease) {
|
||||
return std::unexpected{lease.error()};
|
||||
}
|
||||
|
||||
// Map every output path across the entire graph to its producer action ID
|
||||
// so we can detect unordered generated inputs discovered via depfiles (Plan 03/06).
|
||||
std::map<std::filesystem::path, std::string> all_output_producers;
|
||||
for (const auto &act : graph.actions) {
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
all_output_producers[out.lexically_normal()] = act.id;
|
||||
}
|
||||
}
|
||||
|
||||
// Build subgraph dependency tables over selected_indices.
|
||||
std::set<std::size_t> selected_set(selected_indices.begin(), selected_indices.end());
|
||||
std::map<std::size_t, std::size_t> in_degree;
|
||||
std::map<std::size_t, std::vector<std::size_t>> dependents;
|
||||
for (const std::size_t idx : selected_indices) {
|
||||
in_degree[idx] = 0;
|
||||
}
|
||||
for (const std::size_t idx : selected_indices) {
|
||||
for (const auto &dep_id : graph.actions[idx].dependencies) {
|
||||
const auto dit = graph.action_index_by_id.find(dep_id);
|
||||
if (dit != graph.action_index_by_id.end() && selected_set.contains(dit->second)) {
|
||||
++in_degree[idx];
|
||||
dependents[dit->second].push_back(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::size_t worker_count =
|
||||
std::min(selected_indices.size(),
|
||||
options.jobs > 0 ? options.jobs
|
||||
: std::max<std::size_t>(1, std::thread::hardware_concurrency()));
|
||||
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::queue<std::size_t> ready;
|
||||
for (const std::size_t idx : selected_indices) {
|
||||
if (in_degree[idx] == 0) {
|
||||
ready.push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
std::stop_source internal_stop;
|
||||
std::stop_callback forward_stop(external_stop, [&] { internal_stop.request_stop(); });
|
||||
|
||||
std::size_t active_workers = 0;
|
||||
std::size_t completed_count = 0;
|
||||
bool abort_scheduling = false;
|
||||
|
||||
auto emit_event = [&](ExecutionEvent::Kind kind, const Graph::ActionNode &act,
|
||||
std::size_t completed, std::string msg = {}) {
|
||||
if (options.on_event) {
|
||||
options.on_event(ExecutionEvent{kind, act.id, act.target_name, completed,
|
||||
selected_indices.size(), std::move(msg)});
|
||||
}
|
||||
};
|
||||
|
||||
auto run_one_action = [&](const Graph::ActionNode &act) -> ActionExecutionResult {
|
||||
const auto timer = Void::Time::Stopwatch::started();
|
||||
ActionExecutionResult res;
|
||||
res.action_id = act.id;
|
||||
res.target_name = act.target_name;
|
||||
|
||||
if (internal_stop.stop_requested()) {
|
||||
res.cancelled = true;
|
||||
res.error_message = "cancelled before start";
|
||||
return res;
|
||||
}
|
||||
|
||||
const std::string effective_key = compute_effective_action_key(act);
|
||||
|
||||
// 1. Cache lookup (ONLY when action is deterministic & cacheable!).
|
||||
if (act.cacheable && !act.nondeterministic && options.use_cache) {
|
||||
auto cached = state.lookup_action(effective_key);
|
||||
if (cached && cached->has_value()) {
|
||||
const auto &rec = **cached;
|
||||
if (verify_discovered_inputs_unchanged(rec.discovered_inputs)) {
|
||||
if (verify_outputs_match_record(act, rec) ||
|
||||
restore_outputs_from_cache(act, rec, state)) {
|
||||
res.succeeded = true;
|
||||
res.from_cache = true;
|
||||
res.exit_code = 0;
|
||||
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Prepare output directories and response file.
|
||||
std::error_code ec;
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
if (out.has_parent_path()) {
|
||||
std::filesystem::create_directories(out.parent_path(), ec);
|
||||
}
|
||||
// Critical invariant (Plan 03): remove pre-existing archive before `ar rcsD`
|
||||
// so deleted object files never linger as stale archive members!
|
||||
if (act.kind == Graph::ActionKind::Archive) {
|
||||
std::filesystem::remove(out, ec);
|
||||
}
|
||||
}
|
||||
if (act.depfile && act.depfile->has_parent_path()) {
|
||||
std::filesystem::create_directories(act.depfile->parent_path(), ec);
|
||||
std::filesystem::remove(*act.depfile, ec);
|
||||
}
|
||||
if (act.response_file) {
|
||||
auto wrote_rsp =
|
||||
Platform::atomic_write_file(*act.response_file, act.response_file_content, false);
|
||||
if (!wrote_rsp) {
|
||||
res.error_message = "failed writing response file: " + wrote_rsp.error().message();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Execute subprocess under Linux process-group supervisor.
|
||||
Platform::ProcessRequest preq;
|
||||
preq.executable = act.executable;
|
||||
preq.arguments = act.arguments;
|
||||
if (!act.working_directory.empty()) {
|
||||
preq.working_directory = act.working_directory;
|
||||
}
|
||||
preq.environment.mode = Platform::EnvPolicyMode::Inherit;
|
||||
preq.environment.set_vars = act.environment;
|
||||
preq.timeout = options.action_timeout;
|
||||
|
||||
auto proc = Platform::run_supervised(preq, internal_stop.get_token());
|
||||
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
|
||||
if (!proc) {
|
||||
res.error_message = proc.error().message();
|
||||
return res;
|
||||
}
|
||||
|
||||
res.stdout_data = std::move(proc->stdout_data);
|
||||
res.stderr_data = std::move(proc->stderr_data);
|
||||
res.exit_code = proc->exit_code;
|
||||
res.term_signal = proc->term_signal;
|
||||
res.cancelled = proc->cancelled;
|
||||
res.timed_out = proc->timed_out;
|
||||
|
||||
if (proc->exec_failed) {
|
||||
res.error_message = proc->exec_error_message;
|
||||
return res;
|
||||
}
|
||||
if (proc->cancelled) {
|
||||
res.error_message = "action cancelled";
|
||||
return res;
|
||||
}
|
||||
if (proc->timed_out) {
|
||||
res.error_message = "action timed out";
|
||||
return res;
|
||||
}
|
||||
if (proc->overflowed) {
|
||||
res.error_message = "action output exceeded capture limit";
|
||||
return res;
|
||||
}
|
||||
if (!proc->succeeded()) {
|
||||
res.error_message = proc->term_signal != 0
|
||||
? std::format("terminated by signal {}", proc->term_signal)
|
||||
: std::format("exited with status {}", proc->exit_code);
|
||||
return res;
|
||||
}
|
||||
|
||||
// 4. Validate ALL declared outputs exist after zero exit!
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
auto meta = Platform::stat_lstat(out);
|
||||
if (!meta || !meta->exists || !meta->is_regular) {
|
||||
res.error_message =
|
||||
std::format("action '{}' exited 0 but required output '{}' is missing", act.id,
|
||||
out.string());
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Parse depfile (if declared) and verify no unordered generated producer escaped DAG!
|
||||
std::map<std::string, std::string, std::less<>> discovered_inputs;
|
||||
if (act.depfile && std::filesystem::exists(*act.depfile, ec)) {
|
||||
auto deps_res = parse_depfile(*act.depfile);
|
||||
if (!deps_res) {
|
||||
res.error_message = std::format("action '{}' produced invalid depfile: {}", act.id,
|
||||
deps_res.error().message());
|
||||
return res;
|
||||
}
|
||||
const auto ancestors = collect_ancestors(graph, act.id);
|
||||
for (const auto &dep_raw : *deps_res) {
|
||||
const auto dep_abs = dep_raw.is_absolute()
|
||||
? dep_raw.lexically_normal()
|
||||
: (act.working_directory / dep_raw).lexically_normal();
|
||||
if (const auto prod_it = all_output_producers.find(dep_abs);
|
||||
prod_it != all_output_producers.end() && prod_it->second != act.id &&
|
||||
!ancestors.contains(prod_it->second)) {
|
||||
res.error_message = std::format(
|
||||
"action '{}' read generated file '{}' from unordered producer '{}' "
|
||||
"(declare an explicit dependency/depends_on)",
|
||||
act.id, dep_abs.string(), prod_it->second);
|
||||
return res;
|
||||
}
|
||||
if (auto digest = Util::sha256_file_hex(dep_abs); digest) {
|
||||
discovered_inputs[dep_abs.string()] = std::move(*digest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Publish outputs to CAS BEFORE recording success (only for cacheable actions).
|
||||
if (act.cacheable && !act.nondeterministic) {
|
||||
State::ActionSuccessRecord rec;
|
||||
rec.action_key = effective_key;
|
||||
rec.profile_identity = graph.profile_identity;
|
||||
rec.target_name = act.target_name;
|
||||
rec.discovered_inputs = std::move(discovered_inputs);
|
||||
rec.recorded_epoch = std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch())
|
||||
.count();
|
||||
|
||||
for (const auto &out : act.declared_outputs) {
|
||||
auto stored = state.store_blob_from_file(out);
|
||||
if (!stored) {
|
||||
res.error_message = std::format("failed publishing output '{}' to CAS: {}",
|
||||
out.string(), stored.error().message());
|
||||
return res;
|
||||
}
|
||||
rec.outputs[out.string()] = std::move(*stored);
|
||||
}
|
||||
auto committed = state.record_action_success(rec);
|
||||
if (!committed) {
|
||||
res.error_message = std::format("failed committing action success record: {}",
|
||||
committed.error().message());
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
res.succeeded = true;
|
||||
return res;
|
||||
};
|
||||
|
||||
auto worker_loop = [&] {
|
||||
for (;;) {
|
||||
std::size_t idx = 0;
|
||||
{
|
||||
std::unique_lock lk{mu};
|
||||
cv.wait(lk, [&] {
|
||||
return !ready.empty() || abort_scheduling || internal_stop.stop_requested() ||
|
||||
(active_workers == 0 && ready.empty());
|
||||
});
|
||||
if (abort_scheduling || internal_stop.stop_requested()) {
|
||||
return;
|
||||
}
|
||||
if (ready.empty()) {
|
||||
if (active_workers == 0) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
idx = ready.front();
|
||||
ready.pop();
|
||||
++active_workers;
|
||||
}
|
||||
|
||||
const auto &act = graph.actions[idx];
|
||||
emit_event(ExecutionEvent::Kind::ActionStarted, act, completed_count);
|
||||
auto ares = run_one_action(act);
|
||||
|
||||
{
|
||||
std::lock_guard lk{mu};
|
||||
--active_workers;
|
||||
++completed_count;
|
||||
if (ares.succeeded) {
|
||||
if (ares.from_cache) {
|
||||
++report.cached_count;
|
||||
emit_event(ExecutionEvent::Kind::ActionCached, act, completed_count);
|
||||
} else {
|
||||
++report.executed_count;
|
||||
emit_event(ExecutionEvent::Kind::ActionSucceeded, act, completed_count);
|
||||
}
|
||||
for (const std::size_t dep_idx : dependents[idx]) {
|
||||
if (--in_degree[dep_idx] == 0) {
|
||||
ready.push(dep_idx);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
++report.failed_count;
|
||||
if (ares.cancelled) {
|
||||
report.cancelled = true;
|
||||
}
|
||||
if (report.diagnostic.empty()) {
|
||||
report.diagnostic = act.id + ": " + ares.error_message;
|
||||
}
|
||||
emit_event(ExecutionEvent::Kind::ActionFailed, act, completed_count,
|
||||
ares.error_message);
|
||||
if (options.fail_fast) {
|
||||
abort_scheduling = true;
|
||||
internal_stop.request_stop();
|
||||
}
|
||||
}
|
||||
report.results.push_back(std::move(ares));
|
||||
}
|
||||
cv.notify_all();
|
||||
}
|
||||
};
|
||||
|
||||
Void::Concurrency::ThreadPool pool{worker_count};
|
||||
std::vector<std::future<void>> worker_futures;
|
||||
worker_futures.reserve(worker_count);
|
||||
for (std::size_t w = 0; w < worker_count; ++w) {
|
||||
worker_futures.push_back(pool.submit(worker_loop));
|
||||
}
|
||||
for (auto &f : worker_futures) {
|
||||
f.get();
|
||||
}
|
||||
|
||||
if (external_stop.stop_requested()) {
|
||||
report.cancelled = true;
|
||||
}
|
||||
report.succeeded = (report.failed_count == 0) && !report.cancelled &&
|
||||
(report.executed_count + report.cached_count == report.total_selected);
|
||||
if (!report.succeeded && report.diagnostic.empty()) {
|
||||
report.diagnostic = report.cancelled ? "build cancelled" : "build incomplete";
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Execution
|
||||
Reference in new issue
Block a user