Files
Build-System/src/Execution/Scheduler.cpp
T
faumaray 09c0a91d1d
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 4s
feat(cache): add shared HTTP action cache and parallel snapshot hashing
- D1: RemoteCasClient + registry /api/v1/cas endpoints with bearer auth and digest verification, StateStore remote action/blob APIs, build-path-independent action keys, --remote-cache CLI
- D2: parallel snapshot revalidation hashing via Void::Concurrency::ThreadPool
- Verified in Docker GCC 16: 8/8 CTest suites, cross-build-dir 100% cache hit, 5001-file warm no-op 374 ms
- Fix self-host recipe source list for RemoteCache.cpp and accept GCC 16 -lgcc_s_asneeded
2026-12-03 12:36:21 +03:00

950 lines
39 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/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Data/StrictJson.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;
}
// Build-path-independent path mapping used for shared remote cache keys and records.
// Longest prefix wins so nested build/root prefixes are replaced before their parents.
struct PathMapper {
std::vector<std::pair<std::string, std::string>> pairs;
[[nodiscard]] std::string normalize(std::string_view input) const {
std::string out{input};
for (const auto &[prefix, token] : pairs) {
std::size_t pos = 0;
while ((pos = out.find(prefix, pos)) != std::string::npos) {
out.replace(pos, prefix.size(), token);
pos += token.size();
}
}
return out;
}
[[nodiscard]] std::string denormalize(std::string_view input) const {
std::string out{input};
for (const auto &[prefix, token] : pairs) {
std::size_t pos = 0;
while ((pos = out.find(token, pos)) != std::string::npos) {
out.replace(pos, token.size(), prefix);
pos += prefix.size();
}
}
return out;
}
};
PathMapper make_path_mapper(const Graph::BuildGraph &graph) {
std::vector<std::pair<std::string, std::string>> pairs;
auto add = [&](const std::filesystem::path &path, std::string token) {
if (!path.empty()) {
pairs.emplace_back(path.lexically_normal().string(), std::move(token));
}
};
add(graph.snapshot_materialized_root, "${SNAPSHOT}");
add(graph.profile_build_dir, "${PROFILE}");
if (!graph.profile_build_dir.empty()) {
// The whole build root (probes, .vbs state, other profiles) must stay portable too.
add(graph.profile_build_dir.parent_path().parent_path(), "${BUILD}");
}
add(graph.project_root, "${PROJECT}");
std::ranges::sort(pairs,
[](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
return PathMapper{std::move(pairs)};
}
std::string portable_executable(const std::filesystem::path &exe, const PathMapper &mapper) {
const std::string raw = exe.string();
const std::string normalized = mapper.normalize(raw);
if (normalized == raw && exe.has_filename()) {
// Toolchain identity already covers the compiler; keep external tool paths portable.
return exe.filename().string();
}
return normalized;
}
// Portable action identity: logical action id + flags + input content digests, with all
// build-root/project-root prefixes normalized away. Absolute output paths are excluded.
std::string compute_remote_action_key(const Graph::ActionNode &action,
const Graph::BuildGraph &graph, RunDigestCache &digest_cache,
const PathMapper &mapper) {
Util::Sha256Hasher hasher;
hasher.update_length_prefixed("vbs-remote-action-v1");
hasher.update_length_prefixed(graph.profile_identity);
hasher.update_length_prefixed(graph.toolchain.identity_hash);
hasher.update_length_prefixed(action.id);
hasher.update_u64(static_cast<std::uint64_t>(action.kind));
hasher.update_length_prefixed(portable_executable(action.executable, mapper));
hasher.update_u64(action.arguments.size());
for (const auto &arg : action.arguments) {
hasher.update_length_prefixed(mapper.normalize(arg));
}
hasher.update_length_prefixed(mapper.normalize(action.response_file_content));
hasher.update_u64(action.environment.size());
for (const auto &[k, v] : action.environment) {
hasher.update_length_prefixed(k);
hasher.update_length_prefixed(mapper.normalize(v));
}
hasher.update_u64(action.declared_inputs.size());
for (const auto &in : action.declared_inputs) {
hasher.update_length_prefixed(mapper.normalize(in.string()));
if (auto digest = digest_cache.hash_file(in); digest) {
hasher.update_length_prefixed(*digest);
} else {
hasher.update_length_prefixed("<missing>");
}
}
hasher.update_u64(action.nondeterministic ? 1u : 0u);
return hasher.finalize_hex();
}
std::string serialize_remote_record(const State::ActionSuccessRecord &record,
const Graph::ActionNode &action, const PathMapper &mapper,
std::string_view remote_key) {
using Util::json_array;
using Util::json_quote;
std::vector<State::BlobRef> ordered_outputs;
ordered_outputs.reserve(action.declared_outputs.size());
for (const auto &out : action.declared_outputs) {
const auto it = record.outputs.find(out.string());
if (it == record.outputs.end()) {
return {};
}
ordered_outputs.push_back(it->second);
}
std::string json = "{\"schema_version\":1,\"action_key\":" + json_quote(remote_key) +
",\"profile_identity\":" + json_quote(record.profile_identity) +
",\"target_name\":" + json_quote(record.target_name) +
",\"recorded_epoch\":" + std::to_string(record.recorded_epoch) +
",\"outputs\":";
json += json_array(ordered_outputs, [](const State::BlobRef &ref) {
return "{\"sha256\":" + json_quote(ref.sha256) + ",\"size\":" + std::to_string(ref.size) +
",\"mode\":" + std::to_string(ref.mode) + '}';
});
json += ",\"discovered_inputs\":[";
bool first = true;
for (const auto &[path, digest] : record.discovered_inputs) {
if (!first) {
json += ',';
}
first = false;
json += "{\"path\":" + json_quote(mapper.normalize(path)) +
",\"sha256\":" + json_quote(digest) + '}';
}
json += "],\"lookup_guards\":";
json += json_array(record.lookup_guards, [&](const Snapshot::LookupGuard &guard) {
std::vector<std::string> roots;
roots.reserve(guard.search_roots.size());
for (const auto &root : guard.search_roots) {
roots.push_back(mapper.normalize(root));
}
return "{\"search_roots\":" + json_array(roots, json_quote) +
",\"lookup_name\":" + json_quote(guard.lookup_name) +
",\"matched_root_index\":" + std::to_string(guard.matched_root_index) +
",\"matched_sha256\":" + json_quote(guard.matched_sha256) + '}';
});
json += '}';
return json;
}
using RemoteJson = Void::Json::Strict::Value;
const RemoteJson *remote_find(const RemoteJson::Object &obj, const std::string &key) {
const auto it = obj.find(key);
return it == obj.end() ? nullptr : &it->second;
}
std::string remote_str(const RemoteJson::Object &obj, const std::string &key) {
const auto *value = remote_find(obj, key);
if (!value) {
return {};
}
const auto *text = std::get_if<std::string>(&value->value);
return text ? *text : std::string{};
}
std::int64_t remote_i64(const RemoteJson::Object &obj, const std::string &key) {
const auto *value = remote_find(obj, key);
if (!value) {
return 0;
}
const auto *number = std::get_if<std::int64_t>(&value->value);
return number ? *number : 0;
}
std::optional<State::ActionSuccessRecord> parse_remote_record(std::string_view json_text,
const Graph::ActionNode &action,
const PathMapper &mapper) {
auto parsed = Void::Json::Strict::parse(json_text);
if (!parsed) {
return std::nullopt;
}
const auto *root = std::get_if<RemoteJson::Object>(&parsed->value);
if (!root) {
return std::nullopt;
}
State::ActionSuccessRecord record;
record.profile_identity = remote_str(*root, "profile_identity");
record.target_name = remote_str(*root, "target_name");
record.recorded_epoch = remote_i64(*root, "recorded_epoch");
const auto *outputs = remote_find(*root, "outputs");
const auto *output_array = outputs ? std::get_if<RemoteJson::Array>(&outputs->value) : nullptr;
if (!output_array || output_array->size() != action.declared_outputs.size()) {
return std::nullopt;
}
for (std::size_t i = 0; i < output_array->size(); ++i) {
const auto *obj = std::get_if<RemoteJson::Object>(&(*output_array)[i].value);
if (!obj) {
return std::nullopt;
}
State::BlobRef ref;
ref.sha256 = remote_str(*obj, "sha256");
ref.size = static_cast<std::uint64_t>(remote_i64(*obj, "size"));
ref.mode = static_cast<std::uint32_t>(remote_i64(*obj, "mode"));
if (ref.sha256.size() != 64) {
return std::nullopt;
}
record.outputs[action.declared_outputs[i].string()] = std::move(ref);
}
if (const auto *discovered = remote_find(*root, "discovered_inputs")) {
if (const auto *array = std::get_if<RemoteJson::Array>(&discovered->value)) {
for (const auto &item : *array) {
const auto *obj = std::get_if<RemoteJson::Object>(&item.value);
if (!obj) {
continue;
}
const auto path = remote_str(*obj, "path");
const auto digest = remote_str(*obj, "sha256");
if (!path.empty() && !digest.empty()) {
record.discovered_inputs[mapper.denormalize(path)] = digest;
}
}
}
}
if (const auto *guards = remote_find(*root, "lookup_guards")) {
if (const auto *array = std::get_if<RemoteJson::Array>(&guards->value)) {
for (const auto &item : *array) {
const auto *obj = std::get_if<RemoteJson::Object>(&item.value);
if (!obj) {
continue;
}
Snapshot::LookupGuard guard;
guard.lookup_name = remote_str(*obj, "lookup_name");
guard.matched_root_index = static_cast<int>(remote_i64(*obj, "matched_root_index"));
guard.matched_sha256 = remote_str(*obj, "matched_sha256");
if (const auto *roots = remote_find(*obj, "search_roots")) {
if (const auto *root_array = std::get_if<RemoteJson::Array>(&roots->value)) {
for (const auto &root_value : *root_array) {
if (const auto *text = std::get_if<std::string>(&root_value.value)) {
guard.search_roots.push_back(mapper.denormalize(*text));
}
}
}
}
record.lookup_guards.push_back(std::move(guard));
}
}
}
return record;
}
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;
const PathMapper path_mapper = make_path_mapper(graph);
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;
}
}
}
}
// 1b. Shared remote action cache lookup (Track D1) on local miss.
if (act.cacheable && !act.nondeterministic && options.use_cache &&
state.has_remote_cache()) {
const std::string remote_key =
compute_remote_action_key(act, graph, digest_cache, path_mapper);
auto remote_json = state.fetch_remote_action(remote_key);
if (remote_json && remote_json->has_value()) {
auto remote_record = parse_remote_record(**remote_json, act, path_mapper);
bool usable = remote_record.has_value();
if (usable) {
for (const auto &entry : remote_record->outputs) {
auto have = state.ensure_remote_blob(entry.second.sha256);
if (!have || !*have) {
usable = false;
break;
}
}
}
if (usable &&
verify_discovered_inputs_unchanged(remote_record->discovered_inputs,
digest_cache) &&
(verify_outputs_match_record(act, *remote_record, digest_cache) ||
restore_outputs_from_cache(act, *remote_record, state, digest_cache))) {
remote_record->action_key = remote_key;
(void)state.record_action_success(*remote_record);
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;
}
// Best-effort publication to the shared remote cache (Track D1): blobs first,
// then the action record. Cache upload failures never fail the build.
if (state.has_remote_cache()) {
const std::string remote_key =
compute_remote_action_key(act, graph, digest_cache, path_mapper);
bool uploaded = true;
for (const auto &out : act.declared_outputs) {
const auto it = rec.outputs.find(out.string());
if (it == rec.outputs.end()) {
uploaded = false;
break;
}
auto pushed = state.publish_remote_blob(it->second.sha256);
if (!pushed) {
Void::Log::warn("Remote", "Skipping remote cache upload for '{}': {}",
act.id, pushed.error().message());
uploaded = false;
break;
}
}
if (uploaded) {
const auto json = serialize_remote_record(rec, act, path_mapper, remote_key);
if (!json.empty()) {
auto pushed = state.publish_remote_action(remote_key, json);
if (!pushed) {
Void::Log::warn("Remote", "Skipping remote action record for '{}': {}",
act.id, pushed.error().message());
}
}
}
}
}
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