diff --git a/include/Void/Build/Execution/Scheduler.hpp b/include/Void/Build/Execution/Scheduler.hpp index ac4510b..46c12ef 100644 --- a/include/Void/Build/Execution/Scheduler.hpp +++ b/include/Void/Build/Execution/Scheduler.hpp @@ -62,6 +62,30 @@ struct ExecutionReport { std::string diagnostic; }; +// Why an action would run (or be reused) on the next build: the explain report answers +// "what changed?" without executing anything. +struct ActionExplanation { + std::string action_id; + std::string target_name; + std::string label; + std::string action_key; + std::string command; + bool cacheable{true}; + bool would_run{false}; + bool restorable{false}; // outputs can be restored from the CAS without executing + bool remote_hit{false}; // a shared remote cache holds this action + std::string reason; + std::vector changed_inputs; + std::vector changed_outputs; +}; + +struct ExplainReport { + std::size_t total{0}; + std::size_t up_to_date{0}; + std::size_t would_run{0}; + std::vector actions; +}; + // Parses a GCC/Clang GNU Make depfile (.d) into its list of dependency file paths. [[nodiscard]] Void::Result::Result, Void::Result::Error> parse_depfile(const std::filesystem::path &depfile_path); @@ -72,4 +96,11 @@ parse_depfile(const std::filesystem::path &depfile_path); execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, const ExecutionOptions &options = {}, std::stop_token stop = {}); +// Explains, without executing anything, why each selected action would run or be reused: +// cache-record presence, changed discovered inputs, changed/missing outputs, and whether a +// shared remote cache holds the action. +[[nodiscard]] Void::Result::Result +explain_graph(const Graph::BuildGraph &graph, State::StateStore &state, + const ExecutionOptions &options = {}); + } // namespace Void::Build::Execution diff --git a/src/Execution/Scheduler.cpp b/src/Execution/Scheduler.cpp index 5d99371..3288dfc 100644 --- a/src/Execution/Scheduler.cpp +++ b/src/Execution/Scheduler.cpp @@ -130,8 +130,7 @@ bool restore_outputs_from_cache(const Graph::ActionNode &action, // 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> pairs; +struct PathMapper { std::vector> pairs; [[nodiscard]] std::string normalize(std::string_view input) const { std::string out{input}; @@ -954,4 +953,130 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, return report; } +Void::Result::Result +explain_graph(const Graph::BuildGraph &graph, State::StateStore &state, + const ExecutionOptions &options) { + auto selected_indices_res = graph.select_action_closure(options.selected_targets); + if (!selected_indices_res) { + return std::unexpected{selected_indices_res.error()}; + } + + const auto label_for = [&](const Graph::ActionNode &act) -> std::string { + const 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; + }; + + ExplainReport report; + RunDigestCache digest_cache; + const PathMapper path_mapper = make_path_mapper(graph); + + for (const std::size_t idx : *selected_indices_res) { + const auto &act = graph.actions[idx]; + ActionExplanation ex; + ex.action_id = act.id; + ex.target_name = act.target_name; + ex.label = label_for(act); + ex.cacheable = act.cacheable && !act.nondeterministic; + ex.action_key = compute_effective_action_key(act, digest_cache); + ex.command = act.executable.string(); + for (const auto &arg : act.arguments) { + ex.command += ' '; + ex.command += arg; + } + + if (!ex.cacheable) { + ex.would_run = true; + ex.reason = act.nondeterministic ? "nondeterministic action (never cached)" + : "action is not cacheable"; + } else { + auto cached = state.lookup_action(ex.action_key); + if (!cached) { + return std::unexpected{cached.error()}; + } + if (!cached->has_value()) { + ex.would_run = true; + ex.reason = "no cached result for this action key"; + if (state.has_remote_cache()) { + const std::string remote_key = + compute_remote_action_key(act, graph, digest_cache, path_mapper); + auto remote = state.fetch_remote_action(remote_key); + if (remote && remote->has_value()) { + ex.remote_hit = true; + ex.reason += " (available in the shared remote cache)"; + } + } + } else { + const auto &rec = **cached; + for (const auto &[path_str, expected_sha] : rec.discovered_inputs) { + const auto actual = digest_cache.hash_file(std::filesystem::path{path_str}); + if (!actual) { + ex.changed_inputs.push_back(path_str + " (missing)"); + } else if (*actual != expected_sha) { + ex.changed_inputs.push_back(path_str + " (modified)"); + } + } + for (const auto &out : act.declared_outputs) { + const auto it = rec.outputs.find(out.string()); + if (it == rec.outputs.end()) { + ex.changed_outputs.push_back(out.string() + " (not recorded)"); + continue; + } + const auto actual = digest_cache.hash_file(out); + if (!actual) { + ex.changed_outputs.push_back(out.string() + " (missing)"); + } else if (*actual != it->second.sha256) { + ex.changed_outputs.push_back(out.string() + " (modified)"); + } + } + if (!ex.changed_inputs.empty()) { + ex.would_run = true; + ex.reason = "inputs changed"; + } else if (!ex.changed_outputs.empty()) { + ex.restorable = true; + ex.reason = "outputs changed or missing (restorable from the cache)"; + } else { + ex.reason = "up to date"; + } + } + } + + if (ex.would_run) { + ++report.would_run; + } else { + ++report.up_to_date; + } + report.actions.push_back(std::move(ex)); + } + report.total = report.actions.size(); + return report; +} + } // namespace Void::Build::Execution diff --git a/src/Main.cpp b/src/Main.cpp index 38cee8b..de70f3b 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -68,8 +68,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -381,7 +383,9 @@ struct TestRunRecord { std::string profile; std::string name; bool passed{false}; + bool timed_out{false}; int exit_code{-1}; + int attempts{1}; double elapsed_ms{0}; std::string output; }; @@ -415,6 +419,14 @@ struct BuildCmdOptions { std::optional cdash_build_arg; std::optional cdash_output_arg; std::string test_timeout_arg{"300"}; + std::optional repeat_arg; + std::string retry_arg{"0"}; + bool shuffle{false}; + std::optional shuffle_seed_arg; + bool stop_on_failure{false}; + bool explain{false}; + std::string explain_format{"text"}; + std::optional trace_arg; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -431,9 +443,88 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { << "' (expected 1..86400 seconds)\n"; return 2; } + // Test repetition controls (CTest/Meson parity): --repeat MODE[:N], --retry N, + // --shuffle [--shuffle-seed N] and --stop-on-failure. + enum class RepeatMode { None, UntilFail, UntilPass, AfterTimeout }; + RepeatMode repeat_mode = RepeatMode::None; + int repeat_count = 1; + if (opts.repeat_arg && !opts.repeat_arg->empty()) { + std::string mode_text = *opts.repeat_arg; + std::string count_text; + if (const auto colon = mode_text.find(':'); colon != std::string::npos) { + count_text = mode_text.substr(colon + 1); + mode_text = mode_text.substr(0, colon); + } + if (mode_text == "until-fail") { + repeat_mode = RepeatMode::UntilFail; + } else if (mode_text == "until-pass") { + repeat_mode = RepeatMode::UntilPass; + } else if (mode_text == "after-timeout") { + repeat_mode = RepeatMode::AfterTimeout; + } else { + std::cerr << cmd_name << ": invalid --repeat mode '" << mode_text + << "' (expected until-fail, until-pass or after-timeout)\n"; + return 2; + } + repeat_count = 2; + if (!count_text.empty() && + (!Void::Str::to_int(count_text, repeat_count) || repeat_count < 1 || + repeat_count > 100)) { + std::cerr << cmd_name << ": invalid --repeat count '" << count_text + << "' (expected 1..100)\n"; + return 2; + } + } + int retry_count = 0; + if (!Void::Str::to_int(opts.retry_arg, retry_count) || retry_count < 0 || retry_count > 10) { + std::cerr << cmd_name << ": invalid --retry value '" << opts.retry_arg + << "' (expected 0..10)\n"; + return 2; + } + std::optional shuffle_seed; + if (opts.shuffle && opts.shuffle_seed_arg && !opts.shuffle_seed_arg->empty()) { + std::uint64_t parsed_seed = 0; + const auto &text = *opts.shuffle_seed_arg; + const auto [ptr, ec] = std::from_chars(text.data(), text.data() + text.size(), parsed_seed); + if (ec != std::errc{} || ptr != text.data() + text.size()) { + std::cerr << cmd_name << ": invalid --shuffle-seed '" << text + << "' (expected an unsigned integer)\n"; + return 2; + } + shuffle_seed = parsed_seed; + } + std::vector test_records; const auto total_sw = Void::Time::Stopwatch::started(); + // Chrome-trace collection (`--trace FILE`): build phases and per-action spans. + struct TraceEvent { + std::string name; + std::string category; + double ts_us{0}; + double dur_us{0}; + std::string detail; + }; + std::vector trace_events; + std::mutex trace_mutex; + std::map trace_started; + const auto trace_epoch = std::chrono::steady_clock::now(); + const auto trace_now_us = [&] { + return std::chrono::duration(std::chrono::steady_clock::now() - + trace_epoch) + .count(); + }; + const auto trace_phase = [&](std::string name, std::string category, double elapsed_ms, + std::string detail) { + if (!opts.trace_arg) { + return; + } + const double dur = elapsed_ms * 1000.0; + std::lock_guard lock{trace_mutex}; + trace_events.push_back({std::move(name), std::move(category), + std::max(0.0, trace_now_us() - dur), dur, std::move(detail)}); + }; + std::optional compiler_override; if (opts.compiler_arg) { try { @@ -523,6 +614,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } Void::Log::info("Config", "Build description {} ({:.0f} ms)", compiled->recompiled ? "compiled" : "up to date (cached)", cfg_sw.elapsed_ms()); + trace_phase("config", "phase", cfg_sw.elapsed_ms(), "compile the build description"); auto profs = Config::discover_profiles(*compiled, fopts); if (!profs) { @@ -582,11 +674,13 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { ctx.link_options.push_back("--coverage"); } + const auto tc_sw = Void::Time::Stopwatch::started(); auto tc = Toolchain::discover_and_probe(ctx, build_root / ".vbs" / "probes"); if (!tc) { std::cerr << "vbs: " << tc.error().message() << '\n'; return 1; } + trace_phase("toolchain", "phase", tc_sw.elapsed_ms(), "discover and probe the toolchain"); Void::Log::info("Toolchain", "[{}] Using {} ({}) [{}]", prof_name, compiler_name(tc->family), tc->cxx_compiler.string(), tc->version_banner); @@ -601,6 +695,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Void::Log::info("Eval", "[{}] Evaluated {} target(s), {} dependenc(ies) ({:.0f} ms)", prof_name, desc->targets.size(), desc->dependencies.size(), eval_sw.elapsed_ms()); + trace_phase("eval", "phase", eval_sw.elapsed_ms(), "evaluate the project description"); // Load & merge any TOML dependency manifests declared by build.cpp. std::vector toml_deps; @@ -768,6 +863,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Void::Log::info("Snapshot", "[{}] Captured snapshot {} ({} file(s), {:.0f} ms)", prof_name, snap->snapshot_id.substr(0, 12), snap->entries.size(), snap_sw.elapsed_ms()); + trace_phase("snapshot", "phase", snap_sw.elapsed_ms(), "capture the immutable snapshot"); const auto graph_sw = Void::Time::Stopwatch::started(); Graph::GraphLowerOptions gopts{project_root, build_root, &(*snap), @@ -782,6 +878,7 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Void::Log::info("Graph", "[{}] Lowered {} action(s) across {} target(s) ({:.0f} ms)", prof_name, graph->actions.size(), graph->targets.size(), graph_sw.elapsed_ms()); + trace_phase("graph", "phase", graph_sw.elapsed_ms(), "lower the action graph"); // Publish compdb BEFORE compilation (Plan 09: compile failure does NOT undo selection!). Editor::PublishOptions popts; @@ -801,6 +898,111 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { eopts.jobs = jobs; eopts.use_cache = !opts.no_cache; eopts.selected_targets = opts.targets; + if (opts.trace_arg) { + eopts.on_event = [&](const Execution::ExecutionEvent &ev) { + std::lock_guard lock{trace_mutex}; + const double now = trace_now_us(); + if (ev.kind == Execution::ExecutionEvent::Kind::ActionStarted) { + trace_started[ev.action_id] = now; + return; + } + const double dur = static_cast(ev.elapsed.count()) * 1000.0; + double ts = std::max(0.0, now - dur); + if (const auto it = trace_started.find(ev.action_id); it != trace_started.end()) { + ts = it->second; + trace_started.erase(it); + } + const char *category = + ev.kind == Execution::ExecutionEvent::Kind::ActionCached + ? "cache" + : (ev.kind == Execution::ExecutionEvent::Kind::ActionSucceeded ? "action" + : "failed"); + trace_events.push_back({ev.label, category, ts, dur, ev.message}); + }; + } + + if (opts.explain) { + auto explained = Execution::explain_graph(*graph, *state, eopts); + if (!explained) { + std::cerr << "vbs explain: " << explained.error().message() << '\n'; + return 1; + } + const auto json_escape = [](std::string_view text) { + std::string out; + for (const char c : text) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\n': + out += "\\n"; + break; + case '\t': + out += "\\t"; + break; + default: + out.push_back(c); + break; + } + } + return out; + }; + if (opts.explain_format == "json") { + std::string json = std::format( + "{{\"profile\":\"{}\",\"total\":{},\"up_to_date\":{},\"would_run\":{},\"actions\":[", + json_escape(prof_name), explained->total, explained->up_to_date, + explained->would_run); + for (std::size_t i = 0; i < explained->actions.size(); ++i) { + const auto &ex = explained->actions[i]; + if (i > 0) { + json += ','; + } + json += std::format( + "{{\"id\":\"{}\",\"target\":\"{}\",\"label\":\"{}\",\"action_key\":\"{}\"," + "\"cacheable\":{},\"would_run\":{},\"restorable\":{},\"remote_hit\":{}," + "\"reason\":\"{}\",\"changed_inputs\":[", + json_escape(ex.action_id), json_escape(ex.target_name), + json_escape(ex.label), json_escape(ex.action_key), + ex.cacheable ? "true" : "false", ex.would_run ? "true" : "false", + ex.restorable ? "true" : "false", ex.remote_hit ? "true" : "false", + json_escape(ex.reason)); + for (std::size_t j = 0; j < ex.changed_inputs.size(); ++j) { + json += (j > 0 ? "," : "") + std::format("\"{}\"", json_escape(ex.changed_inputs[j])); + } + json += "],\"changed_outputs\":["; + for (std::size_t j = 0; j < ex.changed_outputs.size(); ++j) { + json += (j > 0 ? "," : "") + + std::format("\"{}\"", json_escape(ex.changed_outputs[j])); + } + json += std::format("],\"command\":\"{}\"}}", json_escape(ex.command)); + } + json += "]}"; + std::cout << json << '\n'; + } else { + std::cout << std::format("vbs explain: [{}] {} action(s): {} up to date, {} would run\n", + prof_name, explained->total, explained->up_to_date, + explained->would_run); + for (const auto &ex : explained->actions) { + std::cout << std::format(" {:<11} {}", ex.would_run ? "would run" : "up to date", + ex.label); + if (!ex.reason.empty() && ex.reason != "up to date") { + std::cout << " — " << ex.reason; + } + std::cout << '\n'; + for (const auto &input : ex.changed_inputs) { + std::cout << " input: " << input << '\n'; + } + for (const auto &output : ex.changed_outputs) { + std::cout << " output: " << output << '\n'; + } + } + } + continue; + } + auto rep = Execution::execute_graph(*graph, *state, eopts); if (!rep) { std::cerr << "vbs: " << rep.error().message() << '\n'; @@ -1032,6 +1234,43 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } return false; }; + // Claim order: declaration order, or a seeded shuffle (--shuffle). + std::vector claim_order(test_jobs.size()); + std::iota(claim_order.begin(), claim_order.end(), std::size_t{0}); + if (opts.shuffle) { + const std::uint64_t seed = + shuffle_seed.value_or(static_cast(std::random_device{}())); + std::mt19937_64 rng{seed}; + std::ranges::shuffle(claim_order, rng); + Void::Log::info("Test", "[{}] Shuffled {} test(s) (seed {})", prof_name, + claim_order.size(), seed); + } + const auto run_attempt = [&](const TestJob &job) { + const auto tsw = Void::Time::Stopwatch::started(); + Platform::ProcessRequest treq; + if (wine) { + treq.executable = *wine; + treq.arguments = {job.executable.string()}; + } else { + treq.executable = job.executable; + } + treq.working_directory = project_root; + treq.timeout = std::chrono::seconds{test_timeout_seconds}; + auto tres = Platform::run_supervised(treq); + TestRunRecord record; + record.profile = prof_name; + record.name = job.name; + record.passed = tres.has_value() && tres->succeeded(); + record.elapsed_ms = tsw.elapsed_ms(); + if (tres) { + record.output = tres->stdout_data + tres->stderr_data; + record.exit_code = tres->exit_code; + record.timed_out = tres->timed_out; + } else { + record.output = tres.error().message(); + } + return record; + }; const auto worker = [&] { for (;;) { std::size_t index = 0; @@ -1041,12 +1280,18 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { if (remaining == 0) { return; } - for (; index < test_jobs.size(); ++index) { - if (!claimed[index] && prerequisites_done(index) && - resources_free(index)) { + std::optional pick; + for (const std::size_t candidate : claim_order) { + if (!claimed[candidate] && prerequisites_done(candidate) && + resources_free(candidate)) { + pick = candidate; break; } } + if (!pick) { + continue; // Woken spuriously; wait again. + } + index = *pick; claimed[index] = true; // A failed fixture setup skips its dependents. const bool blocked = @@ -1068,37 +1313,49 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } const auto &job = test_jobs[index]; - Void::Log::info("Test", "[{}] Running test target '{}'...", prof_name, - job.name); - const auto tsw = Void::Time::Stopwatch::started(); - Platform::ProcessRequest treq; - if (wine) { - treq.executable = *wine; - treq.arguments = {job.executable.string()}; - } else { - treq.executable = job.executable; - } - treq.working_directory = project_root; - treq.timeout = std::chrono::seconds{test_timeout_seconds}; - auto tres = Platform::run_supervised(treq); TestRunRecord record; - record.profile = prof_name; - record.name = job.name; - record.passed = tres.has_value() && tres->succeeded(); - record.elapsed_ms = tsw.elapsed_ms(); - if (tres) { - record.output = tres->stdout_data + tres->stderr_data; - record.exit_code = tres->exit_code; - } else { - record.output = tres.error().message(); + double elapsed_total = 0.0; + int attempts = 0; + for (;;) { + ++attempts; + Void::Log::info("Test", "[{}] Running test target '{}' (attempt {})...", + prof_name, job.name, attempts); + record = run_attempt(job); + elapsed_total += record.elapsed_ms; + bool again = false; + switch (repeat_mode) { + case RepeatMode::UntilFail: + again = record.passed && attempts < repeat_count; + break; + case RepeatMode::UntilPass: + again = !record.passed && attempts < repeat_count; + break; + case RepeatMode::AfterTimeout: + again = record.timed_out && attempts < repeat_count; + break; + case RepeatMode::None: + break; + } + if (!again && !record.passed && retry_count > 0 && + attempts <= retry_count) { + again = true; + } + if (!again) { + break; + } + Void::Log::warn("Test", "[{}] Repeating '{}' ({})", prof_name, job.name, + record.passed ? "repeat policy" + : (record.timed_out ? "timed out" : "failed")); } + record.attempts = attempts; + record.elapsed_ms = elapsed_total; const bool passed = record.passed; if (!passed) { - Void::Log::error("Test", "[{}] FAILED '{}' ({:.0f} ms)", prof_name, - job.name, tsw.elapsed_ms()); + Void::Log::error("Test", "[{}] FAILED '{}' after {} attempt(s) ({:.0f} ms)", + prof_name, job.name, attempts, elapsed_total); } else { - Void::Log::info("Test", "[{}] PASSED '{}' ({:.0f} ms)", prof_name, job.name, - tsw.elapsed_ms()); + Void::Log::info("Test", "[{}] PASSED '{}' after {} attempt(s) ({:.0f} ms)", + prof_name, job.name, attempts, elapsed_total); } { std::lock_guard lock{test_mutex}; @@ -1109,6 +1366,22 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { completed[index] = true; failed[index] = !passed; --remaining; + if (!passed && opts.stop_on_failure) { + std::size_t skipped = 0; + for (std::size_t i = 0; i < test_jobs.size(); ++i) { + if (!claimed[i] && !completed[i]) { + claimed[i] = true; + completed[i] = true; + --remaining; + ++skipped; + } + } + if (skipped > 0) { + Void::Log::warn("Test", + "[{}] --stop-on-failure: skipped {} remaining test(s)", + prof_name, skipped); + } + } } test_cv.notify_all(); } @@ -1139,6 +1412,10 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { test_records.push_back(std::move(*record)); } } + if (opts.stop_on_failure && !all_ok) { + Void::Log::warn("Test", "--stop-on-failure: skipping the remaining profiles"); + break; + } } // lcov coverage report from the gcov data produced by the instrumented test binaries. @@ -1291,6 +1568,53 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } + if (opts.trace_arg && !opts.trace_arg->empty()) { + trace_phase("total", "phase", total_sw.elapsed_ms(), "whole invocation"); + const auto json_escape = [](std::string_view text) { + std::string out; + for (const char c : text) { + switch (c) { + case '"': + out += "\\\""; + break; + case '\\': + out += "\\\\"; + break; + case '\n': + out += "\\n"; + break; + case '\t': + out += "\\t"; + break; + default: + out.push_back(c); + break; + } + } + return out; + }; + std::string json = "{\"traceEvents\":["; + for (std::size_t i = 0; i < trace_events.size(); ++i) { + const auto &ev = trace_events[i]; + if (i > 0) { + json += ','; + } + json += std::format( + "{{\"name\":\"{}\",\"cat\":\"{}\",\"ph\":\"X\",\"ts\":{:.0f},\"dur\":{:.0f}," + "\"pid\":1,\"tid\":1,\"args\":{{\"detail\":\"{}\"}}}}", + json_escape(ev.name), json_escape(ev.category), ev.ts_us, ev.dur_us, + json_escape(ev.detail)); + } + json += "],\"displayTimeUnit\":\"ms\"}"; + if (auto written = Platform::atomic_write_file(*opts.trace_arg, json, false); !written) { + std::cerr << "vbs: cannot write trace file: " << written.error().message() << '\n'; + all_ok = false; + } else { + Void::Log::info("Build", "Wrote {} trace event(s) to {}", trace_events.size(), + *opts.trace_arg); + } + } + Void::Log::debug("Build", "Total wall time: {:.2f}s", total_sw.elapsed_ms() / 1000.0); return all_ok ? 0 : 1; } @@ -3833,6 +4157,19 @@ int main(int argc, char **argv) { build_opts.target_arch_arg) .option_default("--test-timeout", "", "Per-test timeout in seconds (1..86400)", build_opts.test_timeout_arg, "300") + .option("--repeat", "", + "Repeat tests: until-fail[:N], until-pass[:N] or after-timeout[:N] (N=1..100)", + build_opts.repeat_arg) + .option_default("--retry", "", "Retry a failed test up to N times (0..10)", + build_opts.retry_arg, "0") + .flag("--shuffle", "", "Run tests in a shuffled order", build_opts.shuffle) + .option("--shuffle-seed", "", "Seed for --shuffle (default: random)", + build_opts.shuffle_seed_arg) + .flag("--stop-on-failure", "", "Stop scheduling tests after the first failure", + build_opts.stop_on_failure) + .option("--trace", "", + "Write a Chrome trace (JSON) of build phases and action spans", + build_opts.trace_arg) .option("--junit", "", "Write a JUnit XML report of test results", build_opts.junit_arg) .option("--coverage", "", "Build with --coverage and write an lcov report to this directory", build_opts.coverage_arg) @@ -3883,6 +4220,11 @@ int main(int argc, char **argv) { configure_build_or_test( root.subcommand("build", "Configure and build selected profiles and targets")); configure_build_or_test(root.subcommand("test", "Build and run declared test targets")); + auto &explain_cmd = + root.subcommand("explain", "Explain why each action would run or be reused"); + configure_build_or_test(explain_cmd); + explain_cmd.option_default("--format", "", "Output format: text (default) or json", + build_opts.explain_format, "text"); auto &describe_cmd = root.subcommand("describe", "Evaluate build.cpp and emit versioned graph summary JSON"); @@ -4478,7 +4820,7 @@ int main(int argc, char **argv) { const std::string_view cmd = parsed.matched_command_path.front(); const bool machine_quiet_default = - (cmd == "describe") || (cmd == "graph") || (cmd == "doctor") || + (cmd == "describe") || (cmd == "graph") || (cmd == "doctor") || (cmd == "explain") || (cmd == "compdb" && parsed.matched_command_path.size() >= 2 && parsed.matched_command_path[1] == "show") || (cmd == "ide" && parsed.matched_command_path.size() >= 2 && @@ -4489,8 +4831,15 @@ int main(int argc, char **argv) { : Void::Log::Level::Info); ConsoleLogGuard log_guard{log_level}; - if (cmd == "build" || cmd == "test") { + if (cmd == "build" || cmd == "test" || cmd == "explain") { const bool run_tests = cmd == "test"; + build_opts.explain = cmd == "explain"; + if (build_opts.explain && build_opts.explain_format != "text" && + build_opts.explain_format != "json") { + std::cerr << "vbs explain: unsupported --format '" << build_opts.explain_format + << "' (expected text or json)\n"; + return 2; + } if (Config::is_workspace_root(std::filesystem::path{build_opts.project_arg})) { return execute_workspace(std::move(build_opts), run_tests); } diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index d755f0f..7e76144 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -28,6 +28,17 @@ check_process(2 "" "unknown subcommand: invalid" invalid) check_process(0 "Usage: vbs build .*--native-foreign.*--profile.*\\(repeatable\\)" "" build --help) check_process(0 "Usage: vbs test " "" test --help) check_process(2 "" "invalid --test-timeout" test --test-timeout 0) +check_process(0 "Usage: vbs test .*--repeat" "" test --help) +check_process(0 "--shuffle" "" test --help) +check_process(0 "--stop-on-failure" "" test --help) +check_process(0 "Usage: vbs explain " "" explain --help) +check_process(0 "--format" "" explain --help) +check_process(2 "" "unsupported --format" explain --format xml) +check_process(0 "--trace" "" build --help) +check_process(2 "" "invalid --repeat mode" test --repeat bogus) +check_process(2 "" "invalid --repeat count" test --repeat until-pass:0) +check_process(2 "" "invalid --retry value" test --retry 99) +check_process(2 "" "invalid --shuffle-seed" test --shuffle --shuffle-seed abc) check_process(0 "Usage: vbs init " "" init --help) check_process(0 "Usage: vbs clean " "" clean --help) check_process(0 "Usage: vbs doctor " "" doctor --help) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index 1447500..e349006 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -3800,3 +3800,272 @@ class DemoPkg(ConanFile): Void::Testing::expect(found_install_output); } } + +// === Test-runner parity: repetition controls, shuffle and stop-on-failure === +VOID_TEST(FullV1Tests, test_repeat_retry_shuffle_and_stop_on_failure) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_repeat_"}; + const auto proj = tmp / "proj"; + const auto bdir = tmp / "build"; + + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.test("t_fail") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"tests/fail.cpp"}); + p.test("t_pass") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"tests/pass.cpp"}); + p.test("t_flaky") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"tests/flaky.cpp"}); +} +)cpp"); + write_file(proj / "tests" / "fail.cpp", + "#include \n" + "int main() {\n" + " std::ofstream log{\"order.log\", std::ios::app};\n" + " log << \"fail\\n\";\n" + " return 1;\n" + "}\n"); + write_file(proj / "tests" / "pass.cpp", + "#include \n" + "int main() {\n" + " std::ofstream log{\"order.log\", std::ios::app};\n" + " log << \"pass\\n\";\n" + " return 0;\n" + "}\n"); + // Fails on its first invocation, passes afterwards (state in the project directory, + // which is the working directory of every test run). + write_file(proj / "tests" / "flaky.cpp", + "#include \n" + "#include \n" + "int main() {\n" + " int prior = 0;\n" + " { std::ifstream in{\"flaky.count\"}; std::string line; while (std::getline(in, line)) ++prior; }\n" + " { std::ofstream out{\"flaky.count\", std::ios::app}; out << \"run\\n\"; }\n" + " { std::ofstream log{\"order.log\", std::ios::app}; log << \"flaky\\n\"; }\n" + " return prior == 0 ? 1 : 0;\n" + "}\n"); + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{300}; + return Platform::run_supervised(req); + }; + const auto count_in_log = [&](std::string_view needle) { + const auto text = Void::FileSystem::read_file(proj / "order.log"); + if (!text) { + return std::size_t{0}; + } + std::size_t count = 0; + for (std::size_t pos = text->find(needle); pos != std::string::npos; + pos = text->find(needle, pos + needle.size())) { + ++count; + } + return count; + }; + const auto reset_logs = [&] { + std::error_code ec; + std::filesystem::remove(proj / "order.log", ec); + std::filesystem::remove(proj / "flaky.count", ec); + }; + + // until-pass: the flaky test must be retried until it passes. + reset_logs(); + auto until_pass = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--target", "t_flaky", "--jobs", "1", "--repeat", "until-pass:3"}); + Void::Testing::expect(until_pass.has_value() && until_pass->succeeded()); + Void::Testing::expect_eq(count_in_log("flaky"), std::size_t{2}); + + // --retry: the same recovery without a repeat policy. + reset_logs(); + auto retry = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--target", "t_flaky", "--jobs", "1", "--retry", "2"}); + Void::Testing::expect(retry.has_value() && retry->succeeded()); + Void::Testing::expect_eq(count_in_log("flaky"), std::size_t{2}); + + // until-fail: a passing test must run N times. + reset_logs(); + auto until_fail = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--target", "t_pass", "--jobs", "1", "--repeat", "until-fail:3"}); + Void::Testing::expect(until_fail.has_value() && until_fail->succeeded()); + Void::Testing::expect_eq(count_in_log("pass"), std::size_t{3}); + + // --shuffle with a fixed seed is deterministic and still runs every selected test. + reset_logs(); + auto shuffled = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--target", "t_pass", "--target", "t_flaky", "--jobs", "1", + "--shuffle", "--shuffle-seed", "42", "--retry", "1"}); + Void::Testing::expect(shuffled.has_value() && shuffled->succeeded()); + const auto first_order = Void::FileSystem::read_file(proj / "order.log"); + Void::Testing::require(first_order.has_value()); + reset_logs(); + auto shuffled_again = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--target", "t_pass", "--target", "t_flaky", "--jobs", "1", + "--shuffle", "--shuffle-seed", "42", "--retry", "1"}); + Void::Testing::expect(shuffled_again.has_value() && shuffled_again->succeeded()); + const auto second_order = Void::FileSystem::read_file(proj / "order.log"); + Void::Testing::require(second_order.has_value()); + Void::Testing::expect(*first_order == *second_order); + + // --stop-on-failure: t_fail is declared first, so with one job nothing else runs. + reset_logs(); + auto stopped = run_vbs({"test", "--project", proj.string(), "--build-dir", bdir.string(), + "--jobs", "1", "--stop-on-failure"}); + Void::Testing::expect(stopped.has_value() && !stopped->succeeded()); + Void::Testing::expect_eq(count_in_log("fail"), std::size_t{1}); + Void::Testing::expect_eq(count_in_log("pass"), std::size_t{0}); + Void::Testing::expect_eq(count_in_log("flaky"), std::size_t{0}); + + // Invalid values are rejected before any project work. + auto bad_repeat = run_vbs({"test", "--project", proj.string(), "--repeat", "bogus"}); + Void::Testing::expect(bad_repeat.has_value() && bad_repeat->exit_code == 2); + auto bad_retry = run_vbs({"test", "--project", proj.string(), "--retry", "99"}); + Void::Testing::expect(bad_retry.has_value() && bad_retry->exit_code == 2); + auto bad_seed = run_vbs({"test", "--project", proj.string(), "--shuffle", "--shuffle-seed", + "not-a-number"}); + Void::Testing::expect(bad_seed.has_value() && bad_seed->exit_code == 2); +} + +// === Explainability: why would an action run, and Chrome-trace output === +VOID_TEST(FullV1Tests, explain_reports_stale_actions_and_trace_writes_chrome_json) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_explain_"}; + const auto proj = tmp / "proj"; + const auto bdir = tmp / "build"; + + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + auto lib = p.static_library("demo").sources({"src/a.cpp"}); + p.executable("app").sources({"src/main.cpp"}).link(lib); +} +)cpp"); + write_file(proj / "src" / "hdr.hpp", "#define EXPECT 3\nint a();\n"); + write_file(proj / "src" / "a.cpp", "#include \"hdr.hpp\"\nint a() { return 1; }\n"); + write_file(proj / "src" / "main.cpp", + "#include \"hdr.hpp\"\nint main() { return a() + 2 == EXPECT ? 0 : 1; }\n"); + + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{300}; + return Platform::run_supervised(req); + }; + const auto json_number = [](const Void::Json::Strict::Value &value) { + if (const auto *integer = std::get_if(&value.value)) { + return static_cast(*integer); + } + if (const auto *real = std::get_if(&value.value)) { + return static_cast(*real); + } + return -1LL; + }; + const auto json_field = [](const Void::Json::Strict::Value::Object &object, + std::string_view key) -> const Void::Json::Strict::Value * { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : &it->second; + }; + + // First build: everything executes. + auto built = run_vbs({"build", "--project", proj.string(), "--build-dir", bdir.string(), + "--jobs", "2"}); + Void::Testing::expect(built.has_value() && built->succeeded()); + + // Nothing changed: every action is up to date. + auto explained = run_vbs({"explain", "--project", proj.string(), "--build-dir", + bdir.string(), "--format", "json"}); + Void::Testing::expect(explained.has_value() && explained->succeeded()); + if (explained) { + auto parsed = Void::Json::Strict::parse(explained->stdout_data); + Void::Testing::require(parsed.has_value()); + const auto *root = std::get_if(&parsed->value); + Void::Testing::require(root != nullptr); + const auto *total = json_field(*root, "total"); + const auto *would_run = json_field(*root, "would_run"); + Void::Testing::require(total != nullptr && would_run != nullptr); + Void::Testing::expect(json_number(*total) >= 3); + Void::Testing::expect_eq(json_number(*would_run), 0LL); + } + + // A changed header must be reported as work to do. + write_file(proj / "src" / "hdr.hpp", "#define EXPECT 4\nint a();\n"); + auto stale = run_vbs({"explain", "--project", proj.string(), "--build-dir", bdir.string(), + "--format", "json"}); + Void::Testing::expect(stale.has_value() && stale->succeeded()); + if (stale) { + auto parsed = Void::Json::Strict::parse(stale->stdout_data); + Void::Testing::require(parsed.has_value()); + const auto *root = std::get_if(&parsed->value); + Void::Testing::require(root != nullptr); + const auto *would_run = json_field(*root, "would_run"); + Void::Testing::require(would_run != nullptr); + Void::Testing::expect(json_number(*would_run) >= 1); + } + + // Text output names the reason. + auto text = run_vbs({"explain", "--project", proj.string(), "--build-dir", bdir.string()}); + Void::Testing::expect(text.has_value() && text->succeeded()); + if (text) { + Void::Testing::expect(text->stdout_data.find("would run") != std::string::npos); + } + + // An unsupported format is rejected before any work. + auto bad = run_vbs({"explain", "--project", proj.string(), "--format", "xml"}); + Void::Testing::expect(bad.has_value() && bad->exit_code == 2); + + // The rebuild writes a Chrome trace with phases and per-action spans. + const auto trace_path = tmp / "trace.json"; + auto traced = run_vbs({"build", "--project", proj.string(), "--build-dir", bdir.string(), + "--jobs", "2", "--trace", trace_path.string()}); + Void::Testing::expect(traced.has_value() && traced->succeeded()); + auto trace_text = Void::FileSystem::read_file(trace_path); + Void::Testing::require(trace_text.has_value()); + auto trace = Void::Json::Strict::parse(*trace_text); + Void::Testing::require(trace.has_value()); + const auto *trace_root = std::get_if(&trace->value); + Void::Testing::require(trace_root != nullptr); + const auto *events = json_field(*trace_root, "traceEvents"); + Void::Testing::require(events != nullptr); + const auto *event_array = std::get_if(&events->value); + Void::Testing::require(event_array != nullptr); + Void::Testing::expect(event_array->size() >= 6); + bool saw_phase = false; + bool saw_action = false; + for (const auto &event : *event_array) { + const auto *object = std::get_if(&event.value); + if (object == nullptr) { + continue; + } + const auto *category = json_field(*object, "cat"); + const auto *phase = json_field(*object, "ph"); + if (category == nullptr || phase == nullptr) { + continue; + } + const auto *category_text = std::get_if(&category->value); + const auto *phase_text = std::get_if(&phase->value); + if (category_text == nullptr || phase_text == nullptr) { + continue; + } + Void::Testing::expect(*phase_text == "X"); + if (*category_text == "phase") { + saw_phase = true; + } + if (*category_text == "action" || *category_text == "cache") { + saw_action = true; + } + } + Void::Testing::expect(saw_phase); + Void::Testing::expect(saw_action); +}