Files
Build-System/src/Execution/Scheduler.cpp
T

631 lines
25 KiB
C++

#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/Log/Log.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>
#include <unordered_map>
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));
}
// Run-scoped thread-safe SHA-256 memo table. Every path is hashed at most once per
// execute_graph() run across all worker threads, and invalidated immediately whenever an
// action actually executes and writes its declared outputs.
class RunDigestCache {
public:
[[nodiscard]] std::optional<std::string> hash_file(const std::filesystem::path &path) {
const std::string key = path.lexically_normal().string();
{
std::lock_guard lk{mu_};
if (const auto it = cache_.find(key); it != cache_.end()) {
return it->second;
}
}
auto d = Util::sha256_file_hex(path);
std::optional<std::string> val =
d ? std::optional<std::string>{std::move(*d)} : std::nullopt;
{
std::lock_guard lk{mu_};
cache_.insert_or_assign(key, val);
}
return val;
}
void invalidate(const std::filesystem::path &path) {
const std::string key = path.lexically_normal().string();
std::lock_guard lk{mu_};
cache_.erase(key);
}
private:
std::mutex mu_;
std::unordered_map<std::string, std::optional<std::string>> cache_;
};
std::string compute_effective_action_key(const Graph::ActionNode &action,
RunDigestCache &digest_cache) {
// 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 = digest_cache.hash_file(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,
RunDigestCache &digest_cache) {
for (const auto &[path_str, expected_sha] : discovered_inputs) {
auto actual = digest_cache.hash_file(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,
RunDigestCache &digest_cache) {
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 = digest_cache.hash_file(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, RunDigestCache &digest_cache) {
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;
}
digest_cache.invalidate(out_path);
}
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;
std::atomic<std::size_t> started_exec_count{0};
bool abort_scheduling = false;
RunDigestCache digest_cache;
auto action_label = [&](const Graph::ActionNode &act) -> std::string {
auto rel_name = [&](const std::filesystem::path &p) -> std::string {
if (p.empty()) {
return act.target_name;
}
if (!graph.project_root.empty() && Platform::path_is_within(graph.project_root, p)) {
return p.lexically_relative(graph.project_root).generic_string();
}
return p.filename().string();
};
switch (act.kind) {
case Graph::ActionKind::Compile:
return std::format("Compile {}", rel_name(!act.logical_source_file.empty()
? act.logical_source_file
: act.logical_output_file));
case Graph::ActionKind::PrecompiledHeader:
return std::format("PCH {}", rel_name(act.logical_source_file));
case Graph::ActionKind::HeaderUnit:
return std::format("HdrUnit {}", rel_name(act.logical_source_file));
case Graph::ActionKind::ModuleScan:
return std::format("ModScan {}", rel_name(act.logical_source_file));
case Graph::ActionKind::ModuleBmi:
return std::format("BMI {}", rel_name(act.logical_source_file));
case Graph::ActionKind::Archive:
return std::format("Archive {}", rel_name(act.logical_output_file));
case Graph::ActionKind::Link:
return std::format("Link {}", rel_name(act.logical_output_file));
case Graph::ActionKind::Custom:
return std::format("Action {}", act.target_name);
}
return act.id;
};
auto emit_event = [&](ExecutionEvent::Kind kind, const Graph::ActionNode &act,
const std::string &label, std::size_t completed,
std::chrono::milliseconds elapsed = {}, std::string msg = {}) {
if (options.on_event) {
options.on_event(ExecutionEvent{kind, act.id, act.target_name, label, completed,
selected_indices.size(), elapsed, std::move(msg)});
}
};
auto run_one_action = [&](const Graph::ActionNode &act,
const std::string &label) -> 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, digest_cache);
// 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, digest_cache)) {
if (verify_outputs_match_record(act, rec, digest_cache) ||
restore_outputs_from_cache(act, rec, state, digest_cache)) {
res.succeeded = true;
res.from_cache = true;
res.exit_code = 0;
res.elapsed = timer.elapsed_as<std::chrono::milliseconds>();
return res;
}
}
}
}
const std::size_t seq = started_exec_count.fetch_add(1, std::memory_order_relaxed) + 1;
Void::Log::info("Build", "[{:>2}/{}] {}", seq, selected_indices.size(), label);
emit_event(ExecutionEvent::Kind::ActionStarted, act, label, seq);
// 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 and drop stale memo entries!
for (const auto &out : act.declared_outputs) {
digest_cache.invalidate(out);
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 = digest_cache.hash_file(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];
const std::string label = action_label(act);
auto ares = run_one_action(act, label);
{
std::lock_guard lk{mu};
--active_workers;
++completed_count;
if (ares.succeeded) {
if (ares.from_cache) {
++report.cached_count;
Void::Log::debug("Build", "[cached] {}", label);
emit_event(ExecutionEvent::Kind::ActionCached, act, label, completed_count,
ares.elapsed);
} else {
++report.executed_count;
Void::Log::debug("Build", "Done {} ({}ms)", label, ares.elapsed.count());
emit_event(ExecutionEvent::Kind::ActionSucceeded, act, label,
completed_count, ares.elapsed);
}
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;
}
Void::Log::error("Build", "FAILED {} ({}): {}", label, act.id,
ares.error_message);
emit_event(ExecutionEvent::Kind::ActionFailed, act, label, completed_count,
ares.elapsed, 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