diff --git a/CMakeLists.txt b/CMakeLists.txt index 3b0d79c..8bd514e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,6 +70,7 @@ add_library(VoidBuild_Core STATIC src/Package/Resolver.cpp src/Package/Manifest.cpp src/Package/Audit.cpp + src/Bench/Bench.cpp src/Test/Doctest.cpp src/Test/Fuzz.cpp src/Sandbox/Linux/NamespaceSandbox.cpp diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 38b98c8..08d761d 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -402,6 +402,7 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B ## Remaining future scope - **Wave 153 (Versioned JSON contracts, G6 start)**: `schemas/` publishes JSON Schemas for `vbs metadata` (`metadata-v1.schema.json`), `vbs describe` (`describe-v1.schema.json`) and `vbs explain --format json` (`explain-v1.schema.json`), all with `additionalProperties: false`; `schemas/README.md` states the versioning rule (a shape change bumps `schema_version` and adds a new `-vN` file, older schemas stay). `vbs describe` now emits a StrictJson graph summary (`schema_version`, roots, profile/compiler/os/arch, counts, target/dependency names) and `vbs explain --format json` carries `schema_version`. `FullV1Tests.json_schemas_validate_metadata_describe_and_explain` validates the emitted documents against the files and proves the validator rejects missing required keys, wrong enums and unexpected properties. +- **Wave 154 (Benchmark targets and regression gates, G1/G8)**: `p.benchmark(name)` adds the `benchmark` target kind (built and linked like an executable). `vbs bench` builds only the benchmark targets (or the `--target` subset), runs each binary `--samples` times (default 3) with `VBS_BENCH=1` and `--max-regression PCT` (default 5), keeps the best wall-clock time per target, and compares against `--baseline FILE` (default `/.vbs/bench_baseline.json`). The first run records the baseline; `--update-baseline` rewrites it (merging unselected entries). Baselines carry os/architecture/compiler/profile and are not compared across machines (warning, gate skipped). `--json FILE` writes a schema-versioned results document (status per benchmark, regression percent, samples). Regressions fail the command. `vbs metadata` bumped to schema v2 (adds the `benchmark` kind and fixes the `header_only` enum), with `metadata-v1.schema.json` retained. Verified by `FullV1Tests.bench_records_baseline_and_enforces_regression_gate` (record, pass, crafted slow/fast baselines, JSON, update, machine mismatch, no-benchmark and invalid-option cases) and the schema test now covers a benchmark target. - **Wave 152 (Test depth and fuzzing, G8)**: `vbs doctest` extracts fenced C++ blocks from `///`, `//!` and Doxygen comment blocks, compiles each as the body of `main()` with `#line` mapping (so errors point at the header), links optional `--source` files and reports block pass/fail. The test runner gained `--shard I/N` (fixture-aware clustering, greedy balancing by the previous run's recorded timings in `/.vbs/test_timings.json`), `--rerun-failed` (reads `/.vbs/last_failed_tests.json` and re-runs only the failed closure), `--known-flaky FILE` (flaky failures are reported but do not fail the run) and coverage gates `--coverage-min PCT` / `--coverage-diff BASE` (lcov summary comparison). `vbs fuzz` builds a libFuzzer target with clang (`-fsanitize=fuzzer,address,undefined`), runs it over a corpus and reports crash artifacts. Verified by `doctest_extracts_compiles_and_runs_blocks`, `test_sharding_partitions_tests_and_records_timings`, `test_rerun_failed_and_known_flaky`, `coverage_gates_enforce_minimum_and_baseline` and `fuzz_builds_targets_and_reports_crashes`. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index a066c3a..76befaf 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -43,7 +43,7 @@ Base HEAD: `fe0d1a6` | Wave 34 (Editor status request) | `editor_status` daemon request + `vbs daemon ide status`: selection state, compdb existence/entry count | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 14/14, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 35 (Daemon compdb use) | `compdb_use` daemon request + `vbs daemon compdb use --profile`: switches the active editor profile under the selection lock | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 15/15, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 36 (Registry binary-variant yank) | `POST .../binaries//yank`, persisted `yanked` flag in detail JSON, client filters yanked variants | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry suite 6/6, full CTest 8/8) | `registry/include/Void/Build/Registry/RegistryService.hpp`, `registry/service/RegistryService.cpp`, `include/Void/Build/Package/RegistryClient.hpp`, `src/Package/RegistryClient.cpp`, `tests/RegistryTests.cpp`, docs | -| Wave 37 (Daemon graph export) | `graph` daemon request + `vbs daemon graph --format dot|json --member`: target dependency graph in a JSON envelope | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 16/16, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | +| Wave 37 (Daemon graph export) | `graph` daemon request + `vbs daemon graph --format dot\|json --member`: target dependency graph in a JSON envelope | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 16/16, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 38 (Daemon test request) | `test` daemon request + `vbs daemon test`: builds, runs declared test targets with bounded output, reports pass/fail counts | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 17/17, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 39 (Compdb entries query) | `compdb_entries` daemon request + `vbs daemon compdb entries --file --limit`: bounded projected entries from the active compdb | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 18/18, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 40 (Authenticated binary downloads) | `download_binary_artifact` bearer auth, `BinaryFetchOptions::bearer_token`, `vbs binaries fetch` token | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 7/7, full CTest 8/8) | `include/Void/Build/Package/{RegistryClient,Fetch}.hpp`, `src/Package/{RegistryClient,Fetch}.cpp`, `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | @@ -153,4 +153,5 @@ Base HEAD: `fe0d1a6` | Wave 151 (Profiles + toolchain pinning) | `Dependency::profile` overrides for native dependency builds (hash-aware), `vbs-toolchain.toml` pin + drift detection (`--locked-toolchain`, `strict`), `vbs profile list\|show\|diff` | COMPLETE & VERIFIED (GCC 16.2; the three G3 tests pass; CLI contracts pass) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `src/Graph/Graph.cpp`, `src/Provider/Provider.cpp`, `include/Void/Build/Toolchain/Pin.hpp`, `src/Toolchain/Pin.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 152 (Test depth + fuzzing) | `vbs doctest` (fenced blocks, `#line` diagnostics, `--source`), `--shard I/N` + timings, `--rerun-failed`, `--known-flaky`, `--coverage-min`/`--coverage-diff`, `vbs fuzz` (libFuzzer) | COMPLETE & VERIFIED (GCC 16.2; doctest/sharding/rerun/coverage tests pass; fuzz test passes under clang 23; CLI contracts pass) | `include/Void/Build/Test/Doctest.hpp`, `src/Test/Doctest.cpp`, `include/Void/Build/Test/Fuzz.hpp`, `src/Test/Fuzz.cpp`, `include/Void/Build/Report/Coverage.hpp`, `src/Report/Coverage.cpp`, `src/Main.cpp`, `tests/{FullV1Tests,CliContracts}`, docs | | Wave 153 (Versioned JSON contracts) | `schemas/{metadata,describe,explain}-v1.schema.json` + versioning rule, `vbs describe` StrictJson graph summary, `vbs explain --format json` schema_version, schema validation test with negative cases | COMPLETE & VERIFIED (GCC 16.2; `json_schemas_validate_metadata_describe_and_explain` passes; vbs_core_tests and CLI contracts pass) | `schemas/`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, docs | +| Wave 154 (Benchmarks + regression gates) | `p.benchmark(name)` target kind, `vbs bench` (build benchmark targets, N samples, `VBS_BENCH=1`), baseline persistence, `--baseline`/`--max-regression`/`--samples`/`--update-baseline`/`--json FILE`, machine-mismatch gate skip, metadata schema v2 (`benchmark` kind, `header_only` fix) | COMPLETE & VERIFIED (GCC 16.2; `bench_records_baseline_and_enforces_regression_gate` and the schema test pass; vbs_core_tests and CLI contracts pass) | `include/Void/Build/Bench/Bench.hpp`, `src/Bench/Bench.cpp`, `include/Void/Build.hpp`, `sdk/Build.cpp`, `src/Graph/Graph.cpp`, `src/Editor/CompDb.cpp`, `src/Install/Installer.cpp`, `src/Main.cpp`, `schemas/`, `tests/{FullV1Tests,CliContracts}`, docs | | Future (Plans 23–24) | Gap closure and superiority tracks | PLANNED (see the plans for per-track acceptance gates) | [23-remaining-upgrade-plan.md](../roadmap/23-remaining-upgrade-plan.md), [24-superiority-tracks.md](../roadmap/24-superiority-tracks.md) | diff --git a/docs/roadmap/24-superiority-tracks.md b/docs/roadmap/24-superiority-tracks.md index 06375c1..6d86fe6 100644 --- a/docs/roadmap/24-superiority-tracks.md +++ b/docs/roadmap/24-superiority-tracks.md @@ -109,8 +109,8 @@ the concrete acceptance gate. ### G1 — Cargo-grade lifecycle CLI *(S–M per command)* -**Status: partially implemented (Wave 147).** Done: `new`, `run`, `metadata`, `why`, `add`, -`remove`, `tree`, `fmt`, `lint`, `audit`, `install-binary`, `--frozen`. Pending: `bench`, `doc`, +**Status: partially implemented (Wave 154).** Done: `new`, `run`, `metadata`, `why`, `add`, +`remove`, `tree`, `fmt`, `lint`, `audit`, `install-binary`, `bench`, `--frozen`. Pending: `doc`, `outdated`, `update -p`, `deny`, `vendor`. **Beats:** Cargo (parity), CMake/Meson/build2 (they have no unified lifecycle). @@ -141,6 +141,10 @@ the concrete acceptance gate. `vbs.json`-free design (all in `build.cpp`). 3. Benchmark target kind (`p.benchmark(name)`) plus result parsing (Google Benchmark JSON, `nanobench`, custom `VBS_BENCH` output) and baseline comparison with tolerance. + **Done (Wave 154):** the `benchmark` target kind, wall-clock samples (`VBS_BENCH=1` is set), + a persisted baseline (`/.vbs/bench_baseline.json`), `--baseline`, `--max-regression`, + `--samples`, `--update-baseline` and `--json FILE`. Structured harness parsing (Google + Benchmark/nanobench) is still pending; wall-clock best-of-N is the current metric. 4. `doc`/`fmt`/`lint` as orchestrated action graphs (so they are cached and parallel), not shell wrappers; `--changed-only` uses the graph's changed inputs. 5. `vendor` reuses the CAS: copy blobs into `vendor/` and rewrite `vbs.lock` sources. @@ -326,11 +330,12 @@ policy violation exits non-zero in CI. **Status: partially implemented (Wave 153).** Done: item 1's `vbs metadata` workspace document (targets, dependencies, features, lockfile, roots) and item 2's published -`schemas/{metadata,describe,explain}-v1.schema.json` with the versioning rule and a -compatibility test (`FullV1Tests.json_schemas_validate_metadata_describe_and_explain`); -`vbs describe` is now a StrictJson graph summary with `schema_version`. Pending: `graph`, -`trace`, `bep`, `doctor` and daemon schemas, the DAP server, the LSP-status request and the -plugin protocol. +`schemas/{metadata-v2,metadata-v1,describe-v1,explain-v1}.schema.json` with the versioning rule +and a compatibility test +(`FullV1Tests.json_schemas_validate_metadata_describe_and_explain`); `vbs describe` is now a +StrictJson graph summary with `schema_version`. Metadata v2 adds the `benchmark` target kind +and corrects the kind enum; v1 is retained. Pending: `graph`, `trace`, `bep`, `doctor` and +daemon schemas, the DAP server, the LSP-status request and the plugin protocol. **Beats:** Cargo (`metadata`), CMake (File API), Meson (introspect) — VBS can expose a single, versioned, cross-cutting model. @@ -401,9 +406,10 @@ registry and lists the same action count; `cache stats` matches the report count **Status: partially implemented (Wave 152).** Done: doctests (`vbs doctest`), sharding with duration-aware partitioning (`vbs test --shard I/N`), `--rerun-failed`, `--known-flaky`, -coverage gates (`--coverage-min`, `--coverage-diff`) and `vbs fuzz` over libFuzzer targets. -Pending: benchmark regression gates (G1 `bench`), AFL support, coverage diff at line level -(currently summary-level), and benchmark result storage. +coverage gates (`--coverage-min`, `--coverage-diff`), `vbs fuzz` over libFuzzer targets and the +benchmark regression gate (`vbs bench --baseline/--max-regression`, baseline storage and +`--json` results, Wave 154). Pending: AFL support, line-level coverage diff and structured +benchmark harness parsing (Google Benchmark/nanobench). **Beats:** CTest (no doctests, no impact analysis), Cargo (no sharding in stable, no coverage gates), everyone (no benchmark regression gate built in). diff --git a/include/Void/Build.hpp b/include/Void/Build.hpp index c6549c0..beb8e76 100644 --- a/include/Void/Build.hpp +++ b/include/Void/Build.hpp @@ -27,7 +27,8 @@ enum class TargetKind { HeaderOnly, ObjectLibrary, CustomAction, - Test + Test, + Benchmark }; enum class SourceKind { File, Glob, ModuleInterface, ModulePartition, HeaderUnit }; enum class LinkKind { Local, Imported }; @@ -391,6 +392,8 @@ class Project { // A target that compiles declared shader sources to SPIR-V (`.shader(...)`). [[nodiscard]] Target shader_bundle(std::string name); [[nodiscard]] Target test(std::string name); + // A runnable benchmark target: built like an executable, executed by `vbs bench`. + [[nodiscard]] Target benchmark(std::string name); // Declares a project feature (additive; defaults are on unless --no-default-features). Project &feature(std::string name, bool default_on = false); Project &feature(FeatureDescription description); diff --git a/include/Void/Build/Bench/Bench.hpp b/include/Void/Build/Bench/Bench.hpp new file mode 100644 index 0000000..eb24941 --- /dev/null +++ b/include/Void/Build/Bench/Bench.hpp @@ -0,0 +1,61 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Build::Bench { + +// One benchmark target's wall-clock measurements (milliseconds, one sample per process run). +struct BenchmarkMeasurement { + std::string name; + std::vector samples_ms; +}; + +// Persisted baseline (`/.vbs/bench_baseline.json` by default). +struct Baseline { + int schema_version{1}; + std::string os; + std::string architecture; + std::string compiler; + std::string profile; + std::map> best_ms; +}; + +struct Comparison { + std::string name; + double best_ms{0}; + std::vector samples_ms; + std::optional baseline_ms; + std::optional regression_pct; + bool regression{false}; + bool is_new{false}; +}; + +[[nodiscard]] double best_of(const std::vector &samples_ms); + +// Loads a baseline; nullopt when the file does not exist. A malformed document or an +// unsupported schema_version is an explicit error. +[[nodiscard]] Void::Result::Result, Void::Result::Error> +load_baseline(const std::filesystem::path &path); + +[[nodiscard]] Void::Result::Result +save_baseline(const std::filesystem::path &path, const Baseline &baseline); + +// Compares the measurements against the baseline. A benchmark counts as a regression when +// (best - baseline) / baseline * 100 exceeds `max_regression_pct`. Benchmarks absent from the +// baseline are reported as new and never fail. +[[nodiscard]] std::vector +compare(const std::vector &measurements, const Baseline &baseline, + double max_regression_pct); + +// True when the baseline was recorded on the same os/architecture/compiler/profile, i.e. when +// comparing wall-clock timings is meaningful. +[[nodiscard]] bool machine_matches(const Baseline &baseline, const Baseline ¤t); + +} // namespace Void::Build::Bench diff --git a/schemas/README.md b/schemas/README.md index aca15d8..9c455f2 100644 --- a/schemas/README.md +++ b/schemas/README.md @@ -4,7 +4,7 @@ Versioned JSON Schemas for the machine-readable `vbs` surfaces: | Command | Schema | | --- | --- | -| `vbs metadata` | [metadata-v1.schema.json](metadata-v1.schema.json) | +| `vbs metadata` | [metadata-v2.schema.json](metadata-v2.schema.json) (current), [metadata-v1.schema.json](metadata-v1.schema.json) (retained) | | `vbs describe` | [describe-v1.schema.json](describe-v1.schema.json) | | `vbs explain --format json` | [explain-v1.schema.json](explain-v1.schema.json) | @@ -27,3 +27,9 @@ Versioned JSON Schemas for the machine-readable `vbs` surfaces: 2. Copy the previous schema to `-vN+1.schema.json` and update it. 3. Add the new document to the schema validation test. 4. Keep the older schema file until the next major release. + +## History + +- **metadata v2** (2026-12-06): added the `benchmark` target kind (G1 `vbs bench`) and corrected + the target-kind enum to the names actually emitted (`header_only`, not + `header_only_library`). v1 is retained unchanged for older consumers. diff --git a/schemas/metadata-v2.schema.json b/schemas/metadata-v2.schema.json new file mode 100644 index 0000000..016ac99 --- /dev/null +++ b/schemas/metadata-v2.schema.json @@ -0,0 +1,154 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://void.build/schemas/metadata-v2.schema.json", + "title": "VoidBuildSystem workspace metadata (schema_version 2)", + "description": "Emitted by `vbs metadata`. Any shape change bumps schema_version and adds a new schema file.", + "type": "object", + "required": [ + "schema_version", + "project_root", + "build_root", + "profile", + "compiler", + "os", + "architecture", + "features", + "targets", + "dependencies", + "lockfile" + ], + "additionalProperties": false, + "properties": { + "schema_version": { "type": "integer", "enum": [2] }, + "project_root": { "type": "string" }, + "build_root": { "type": "string" }, + "profile": { "type": "string" }, + "compiler": { "type": "string" }, + "os": { "type": "string" }, + "architecture": { "type": "string" }, + "features": { + "type": "array", + "items": { + "type": "object", + "required": ["name", "default_on", "description", "enabled"], + "additionalProperties": false, + "properties": { + "name": { "type": "string" }, + "default_on": { "type": "boolean" }, + "description": { "type": "string" }, + "enabled": { "type": "boolean" } + } + } + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "kind", + "sources", + "include_directories", + "links", + "labels", + "required_features", + "install" + ], + "additionalProperties": false, + "properties": { + "name": { "type": "string" }, + "kind": { + "type": "string", + "enum": [ + "executable", + "static_library", + "shared_library", + "header_only", + "object_library", + "custom_action", + "test", + "benchmark" + ] + }, + "sources": { "type": "array", "items": { "type": "string" } }, + "include_directories": { + "type": "array", + "items": { + "type": "object", + "required": ["path", "visibility"], + "additionalProperties": false, + "properties": { + "path": { "type": "string" }, + "visibility": { "type": "string", "enum": ["public", "private"] } + } + } + }, + "links": { + "type": "array", + "items": { + "type": "object", + "required": ["target", "dependency", "visibility"], + "additionalProperties": false, + "properties": { + "target": { "type": "string" }, + "dependency": { "type": "string" }, + "visibility": { "type": "string", "enum": ["public", "private"] } + } + } + }, + "labels": { "type": "array", "items": { "type": "string" } }, + "required_features": { "type": "array", "items": { "type": "string" } }, + "install": { + "type": ["object", "null"], + "required": ["destination", "component"], + "additionalProperties": false, + "properties": { + "destination": { "type": "string" }, + "component": { "type": "string" } + } + } + } + } + }, + "dependencies": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "source", + "package", + "version", + "builder", + "registry", + "features", + "build_dependency" + ], + "additionalProperties": false, + "properties": { + "name": { "type": "string" }, + "source": { + "type": "string", + "enum": ["git", "package", "path", "archive", "conan", "pkgconfig", "unspecified"] + }, + "package": { "type": "string" }, + "version": { "type": "string" }, + "builder": { "type": "string" }, + "registry": { "type": "string" }, + "features": { "type": "array", "items": { "type": "string" } }, + "build_dependency": { "type": "boolean" } + } + } + }, + "lockfile": { + "type": "object", + "required": ["path", "exists"], + "additionalProperties": false, + "properties": { + "path": { "type": "string" }, + "exists": { "type": "boolean" }, + "revision": { "type": "string" } + } + } + } +} diff --git a/sdk/Build.cpp b/sdk/Build.cpp index 56696d5..104f14d 100644 --- a/sdk/Build.cpp +++ b/sdk/Build.cpp @@ -228,6 +228,8 @@ std::string_view target_kind_name(TargetKind kind) { return "custom_action"; case TargetKind::Test: return "test"; + case TargetKind::Benchmark: + return "benchmark"; } throw std::invalid_argument{"unknown target kind"}; } @@ -254,6 +256,9 @@ TargetKind parse_target_kind(std::string_view name) { if (name == "test") { return TargetKind::Test; } + if (name == "benchmark") { + return TargetKind::Benchmark; + } throw std::invalid_argument{"unknown target kind '" + std::string{name} + "'"}; } @@ -1171,6 +1176,10 @@ Target Project::shader_bundle(std::string name) { } Target Project::test(std::string name) { return add_target(std::move(name), TargetKind::Test); } +Target Project::benchmark(std::string name) { + return add_target(std::move(name), TargetKind::Benchmark); +} + Project &Project::feature(std::string name, bool default_on) { FeatureDescription description; description.name = std::move(name); diff --git a/src/Bench/Bench.cpp b/src/Bench/Bench.cpp new file mode 100644 index 0000000..007aca3 --- /dev/null +++ b/src/Bench/Bench.cpp @@ -0,0 +1,168 @@ +#include + +#include +#include +#include +#include + +#include +#include + +namespace Void::Build::Bench { +namespace { + +using JsonValue = Void::Json::Strict::Value; + +Void::Result::Error make_error(std::string message) { + return Void::System::make_system_error(Void::System::SystemErrorCode::invalid_argument, + std::move(message)); +} + +const JsonValue::Object *get_object(const JsonValue::Object &object, std::string_view key) { + const auto it = object.find(std::string{key}); + return it == object.end() ? nullptr : std::get_if(&it->second.value); +} + +std::string get_string(const JsonValue::Object &object, std::string_view key) { + const auto it = object.find(std::string{key}); + if (it == object.end()) { + return {}; + } + const auto *value = std::get_if(&it->second.value); + return value ? *value : std::string{}; +} + +std::optional get_number(const JsonValue &value) { + if (const auto *real = std::get_if(&value.value); real != nullptr) { + return *real; + } + if (const auto *integer = std::get_if(&value.value); integer != nullptr) { + return static_cast(*integer); + } + return std::nullopt; +} + +std::string serialize(const JsonValue::Object &object) { + JsonValue root; + root.value = object; + auto text = Void::Json::Strict::serialize(root); + return text ? *text : std::string{}; +} + +} // namespace + +double best_of(const std::vector &samples_ms) { + return samples_ms.empty() ? 0.0 : *std::ranges::min_element(samples_ms); +} + +Void::Result::Result, Void::Result::Error> +load_baseline(const std::filesystem::path &path) { + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { + return std::optional{}; + } + auto text = Void::FileSystem::read_file(path); + if (!text) { + return std::unexpected{text.error()}; + } + auto parsed = Void::Json::Strict::parse(*text); + if (!parsed) { + return std::unexpected{ + make_error("bench: the baseline '" + path.string() + "' is not valid JSON")}; + } + const auto *root = std::get_if(&parsed->value); + if (root == nullptr) { + return std::unexpected{ + make_error("bench: the baseline must be a JSON object")}; + } + Baseline baseline; + const auto version = get_number(root->contains("schema_version") + ? root->at("schema_version") + : JsonValue{}); + if (!version || *version != 1.0) { + return std::unexpected{make_error( + "bench: unsupported baseline schema_version (expected 1)")}; + } + baseline.schema_version = 1; + baseline.os = get_string(*root, "os"); + baseline.architecture = get_string(*root, "architecture"); + baseline.compiler = get_string(*root, "compiler"); + baseline.profile = get_string(*root, "profile"); + const auto *benchmarks = get_object(*root, "benchmarks"); + if (benchmarks == nullptr) { + return std::unexpected{ + make_error("bench: the baseline has no 'benchmarks' object")}; + } + for (const auto &[name, value] : *benchmarks) { + const auto number = get_number(value); + if (!number || *number < 0.0) { + return std::unexpected{make_error( + "bench: baseline entry '" + name + "' is not a non-negative number")}; + } + baseline.best_ms[name] = *number; + } + return std::optional{std::move(baseline)}; +} + +Void::Result::Result +save_baseline(const std::filesystem::path &path, const Baseline &baseline) { + JsonValue::Object benchmarks; + for (const auto &[name, value] : baseline.best_ms) { + benchmarks[name] = JsonValue{value}; + } + JsonValue::Object root; + root["schema_version"] = JsonValue{std::int64_t{baseline.schema_version}}; + root["os"] = JsonValue{baseline.os}; + root["architecture"] = JsonValue{baseline.architecture}; + root["compiler"] = JsonValue{baseline.compiler}; + root["profile"] = JsonValue{baseline.profile}; + root["benchmarks"] = JsonValue{std::move(benchmarks)}; + const std::string text = serialize(root); + if (text.empty()) { + return std::unexpected{make_error("bench: cannot serialize the baseline")}; + } + std::error_code ec; + if (!path.parent_path().empty()) { + std::filesystem::create_directories(path.parent_path(), ec); + } + if (auto written = Platform::atomic_write_file(path, text + '\n', false); !written) { + return std::unexpected{written.error()}; + } + return {}; +} + +std::vector +compare(const std::vector &measurements, const Baseline &baseline, + double max_regression_pct) { + std::vector comparisons; + comparisons.reserve(measurements.size()); + for (const auto &measurement : measurements) { + Comparison comparison; + comparison.name = measurement.name; + comparison.best_ms = best_of(measurement.samples_ms); + comparison.samples_ms = measurement.samples_ms; + const auto it = baseline.best_ms.find(measurement.name); + if (it == baseline.best_ms.end()) { + comparison.is_new = true; + comparisons.push_back(std::move(comparison)); + continue; + } + comparison.baseline_ms = it->second; + if (it->second <= 0.0) { + comparisons.push_back(std::move(comparison)); + continue; + } + comparison.regression_pct = + (comparison.best_ms - it->second) / it->second * 100.0; + comparison.regression = *comparison.regression_pct > max_regression_pct + 1e-9; + comparisons.push_back(std::move(comparison)); + } + return comparisons; +} + +bool machine_matches(const Baseline &baseline, const Baseline ¤t) { + return baseline.os == current.os && baseline.architecture == current.architecture && + baseline.compiler == current.compiler && baseline.profile == current.profile; +} + +} // namespace Void::Build::Bench diff --git a/src/Editor/CompDb.cpp b/src/Editor/CompDb.cpp index 468258f..3b77a41 100644 --- a/src/Editor/CompDb.cpp +++ b/src/Editor/CompDb.cpp @@ -847,10 +847,12 @@ generate_ide_configs(const Graph::BuildGraph &graph, const IdeConfigOptions &opt continue; } if (t.kind == TargetKind::Executable || t.kind == TargetKind::Test || - t.kind == TargetKind::StaticLibrary || t.kind == TargetKind::SharedLibrary) { + t.kind == TargetKind::Benchmark || t.kind == TargetKind::StaticLibrary || + t.kind == TargetKind::SharedLibrary) { buildable_targets.push_back(t.name); } - if ((t.kind == TargetKind::Executable || t.kind == TargetKind::Test) && + if ((t.kind == TargetKind::Executable || t.kind == TargetKind::Test || + t.kind == TargetKind::Benchmark) && !t.primary_outputs.empty()) { runnables.push_back({t.name, t.kind == TargetKind::Test, t.primary_outputs.front()}); } @@ -1555,6 +1557,7 @@ std::string file_api_target_type(TargetKind kind) { switch (kind) { case TargetKind::Executable: case TargetKind::Test: + case TargetKind::Benchmark: return "EXECUTABLE"; case TargetKind::StaticLibrary: return "STATIC_LIBRARY"; diff --git a/src/Graph/Graph.cpp b/src/Graph/Graph.cpp index be13269..d1ae6e2 100644 --- a/src/Graph/Graph.cpp +++ b/src/Graph/Graph.cpp @@ -2340,7 +2340,7 @@ lower_project_graph(const ProjectDescription &description, graph.action_index_by_id[act.id] = graph.actions.size(); graph.actions.push_back(std::move(act)); } else if (t.kind == TargetKind::Executable || t.kind == TargetKind::SharedLibrary || - t.kind == TargetKind::Test) { + t.kind == TargetKind::Test || t.kind == TargetKind::Benchmark) { // Windows targets use PE conventions (.exe executables, .dll shared libraries). const bool windows_target = Void::Str::to_lower_ascii(description.profile.os) == "windows"; diff --git a/src/Install/Installer.cpp b/src/Install/Installer.cpp index 27c58da..904f06a 100644 --- a/src/Install/Installer.cpp +++ b/src/Install/Installer.cpp @@ -44,6 +44,7 @@ std::string default_dest_for_kind(TargetKind kind) { switch (kind) { case TargetKind::Executable: case TargetKind::Test: + case TargetKind::Benchmark: return "bin"; case TargetKind::StaticLibrary: case TargetKind::SharedLibrary: diff --git a/src/Main.cpp b/src/Main.cpp index fb60afc..60b58d6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -472,6 +473,11 @@ struct BuildCmdOptions { bool rerun_failed{false}; std::optional coverage_min_arg; std::optional coverage_diff_arg; + std::optional bench_baseline_arg; + std::string bench_max_regression_arg{"5"}; + std::string bench_samples_arg{"3"}; + bool bench_update_baseline{false}; + std::optional bench_json_arg; bool publish_editor_selection{true}; bool no_cache{false}; bool locked{false}; @@ -659,8 +665,8 @@ std::set read_flaky_names(const std::vector &files) { return names; } -int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { - const std::string cmd_name = run_tests ? "vbs test" : "vbs build"; +int execute_build_or_test(BuildCmdOptions opts, bool run_tests, bool run_benches = false) { + const std::string cmd_name = run_benches ? "vbs bench" : (run_tests ? "vbs test" : "vbs build"); if (opts.frozen) { // --frozen is the CI-safe combination: the lockfile must exist and no network is used. opts.locked = true; @@ -793,13 +799,39 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { std::cerr << cmd_name << ": --coverage-min and --coverage-diff require --coverage DIR\n"; return 2; } - if (!run_tests && + if (!run_tests && !run_benches && (opts.shard_arg || opts.rerun_failed || !opts.known_flaky_files.empty() || opts.coverage_min_arg || opts.coverage_diff_arg)) { std::cerr << cmd_name << ": test-runner options require 'vbs test'\n"; return 2; } + double bench_max_regression = 5.0; + int bench_samples = 3; + if (run_benches) { + char *end = nullptr; + bench_max_regression = std::strtod(opts.bench_max_regression_arg.c_str(), &end); + if (end == opts.bench_max_regression_arg.c_str() || *end != '\0' || + bench_max_regression < 0.0 || bench_max_regression > 10000.0) { + std::cerr << cmd_name << ": invalid --max-regression value '" + << opts.bench_max_regression_arg << "' (expected 0..10000 percent)\n"; + return 2; + } + if (!Void::Str::to_int(opts.bench_samples_arg, bench_samples) || bench_samples < 1 || + bench_samples > 100) { + std::cerr << cmd_name << ": invalid --samples value '" << opts.bench_samples_arg + << "' (expected 1..100)\n"; + return 2; + } + if (opts.profiles.size() > 1) { + std::cerr << cmd_name << ": bench baseline comparison requires exactly one profile\n"; + return 2; + } + } else if (opts.bench_baseline_arg || opts.bench_update_baseline || opts.bench_json_arg) { + std::cerr << cmd_name << ": benchmark options require 'vbs bench'\n"; + return 2; + } + std::vector test_records; const auto total_sw = Void::Time::Stopwatch::started(); @@ -1363,7 +1395,32 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { Execution::ExecutionOptions eopts; eopts.jobs = jobs; eopts.use_cache = !opts.no_cache; - eopts.selected_targets = opts.targets; + std::vector benchmark_names; + if (run_benches) { + for (const auto &candidate : graph->targets) { + if (candidate.kind == TargetKind::Benchmark && candidate.enabled && + !candidate.primary_outputs.empty()) { + if (opts.targets.empty() || + std::ranges::contains(opts.targets, candidate.name)) { + benchmark_names.push_back(candidate.name); + } + } + } + if (benchmark_names.empty()) { + std::cerr << cmd_name << ": no benchmark targets" + << (opts.targets.empty() ? " declared (use p.benchmark(...))" + : " match --target") + << '\n'; + return 2; + } + if (opts.targets.empty()) { + eopts.selected_targets = benchmark_names; + } else { + eopts.selected_targets = opts.targets; + } + } else { + eopts.selected_targets = opts.targets; + } if (sandbox_mode != Sandbox::SandboxMode::Off) { eopts.sandbox_mode = sandbox_mode; eopts.sandbox_executable = sandbox_executable; @@ -1669,6 +1726,212 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { } } + if (run_benches) { + std::optional wine; + if (windows_cross_target) { + auto resolved = Platform::resolve_executable("wine"); + if (!resolved) { + std::cerr << cmd_name << ": Windows target benchmarks require 'wine' in PATH\n"; + all_ok = false; + continue; + } + wine = *resolved; + } + Bench::Baseline current; + current.os = Toolchain::host_os_name(); + current.architecture = Toolchain::host_architecture_name(); + current.compiler = std::string{compiler_name(ctx.compiler)}; + current.profile = prof_name; + const std::filesystem::path baseline_path = + opts.bench_baseline_arg ? std::filesystem::path{*opts.bench_baseline_arg} + : (build_root / ".vbs" / "bench_baseline.json"); + auto previous = Bench::load_baseline(baseline_path); + if (!previous) { + std::cerr << cmd_name << ": " << previous.error().message() << '\n'; + all_ok = false; + continue; + } + std::vector measurements; + bool bench_ok = true; + for (const auto &name : benchmark_names) { + const Graph::ResolvedTargetSummary *target = nullptr; + for (const auto &candidate : graph->targets) { + if (candidate.name == name) { + target = &candidate; + break; + } + } + if (target == nullptr || target->primary_outputs.empty()) { + std::cerr << cmd_name << ": benchmark '" << name << "' has no output\n"; + bench_ok = false; + break; + } + const auto executable = target->primary_outputs.front(); + std::vector samples; + samples.reserve(static_cast(bench_samples)); + for (int sample = 0; sample < bench_samples; ++sample) { + Platform::ProcessRequest request; + request.executable = wine ? *wine : executable; + if (wine) { + request.arguments.push_back(executable.string()); + } + request.working_directory = project_root; + request.timeout = std::chrono::minutes{10}; + request.environment.mode = Platform::EnvPolicyMode::Inherit; + request.environment.set_vars["VBS_BENCH"] = "1"; + const auto sample_sw = Void::Time::Stopwatch::started(); + auto result = Platform::run_supervised(request); + const double elapsed_ms = sample_sw.elapsed_ms(); + if (!result || !result->succeeded()) { + std::cerr << cmd_name << ": benchmark '" << name << "' failed (exit " + << (result ? result->exit_code : -1) << ")\n"; + if (result) { + std::cerr << result->stdout_data << result->stderr_data; + } else { + std::cerr << result.error().message() << '\n'; + } + bench_ok = false; + break; + } + samples.push_back(elapsed_ms); + } + if (!bench_ok) { + break; + } + measurements.push_back({name, samples}); + std::cout << std::format("vbs bench: {} best {:.3f} ms ({} sample(s))\n", name, + Bench::best_of(samples), samples.size()); + } + if (!bench_ok) { + all_ok = false; + continue; + } + + bool recorded = false; + bool comparable = true; + std::int64_t regressions = 0; + std::vector comparisons; + if (!previous->has_value() || opts.bench_update_baseline) { + if (previous->has_value()) { + current.best_ms = (*previous)->best_ms; + } + for (const auto &measurement : measurements) { + current.best_ms[measurement.name] = Bench::best_of(measurement.samples_ms); + } + if (auto saved = Bench::save_baseline(baseline_path, current); !saved) { + std::cerr << cmd_name << ": " << saved.error().message() << '\n'; + all_ok = false; + continue; + } + recorded = true; + for (const auto &measurement : measurements) { + comparisons.push_back({measurement.name, + Bench::best_of(measurement.samples_ms), + measurement.samples_ms, + std::nullopt, + std::nullopt, + false, + true}); + } + Void::Log::info("Bench", "[{}] recorded baseline {} ({} benchmark(s))", prof_name, + baseline_path.string(), measurements.size()); + } else { + comparable = Bench::machine_matches(**previous, current); + if (!comparable) { + std::cerr << std::format( + "{}: warning: baseline was recorded on {}/{} ({}, {}); skipping the " + "regression gate\n", + cmd_name, (*previous)->os, (*previous)->architecture, + (*previous)->compiler, (*previous)->profile); + } + comparisons = Bench::compare(measurements, **previous, bench_max_regression); + for (const auto &comparison : comparisons) { + if (comparison.is_new) { + std::cout << std::format("vbs bench: {} new (no baseline entry)\n", + comparison.name); + } else if (comparison.regression_pct) { + const bool failed = comparable && comparison.regression; + std::cout << std::format( + "vbs bench: {} {}{:+.2f}% (best {:.3f} ms vs baseline {:.3f} ms)\n", + comparison.name, failed ? "REGRESSED " : "ok ", + *comparison.regression_pct, comparison.best_ms, + *comparison.baseline_ms); + if (failed) { + ++regressions; + } + } + } + if (regressions > 0) { + std::cerr << std::format( + "{}: {} benchmark regression(s) exceed --max-regression {:.1f}%\n", + cmd_name, regressions, bench_max_regression); + all_ok = false; + } else if (comparable) { + Void::Log::info("Bench", "[{}] {} benchmark(s), no regression above {:.1f}%", + prof_name, measurements.size(), bench_max_regression); + } else { + Void::Log::warn("Bench", + "[{}] regression comparison skipped (baseline recorded on a " + "different machine)", + prof_name); + } + } + if (opts.bench_json_arg) { + using JsonValue = Void::Json::Strict::Value; + JsonValue::Array entries; + for (const auto &comparison : comparisons) { + JsonValue::Object entry; + entry["name"] = JsonValue{comparison.name}; + entry["best_ms"] = JsonValue{comparison.best_ms}; + JsonValue::Array samples; + for (const auto sample : comparison.samples_ms) { + samples.push_back(JsonValue{sample}); + } + entry["samples_ms"] = JsonValue{std::move(samples)}; + entry["baseline_ms"] = comparison.baseline_ms + ? JsonValue{*comparison.baseline_ms} + : JsonValue{}; + entry["regression_pct"] = comparison.regression_pct + ? JsonValue{*comparison.regression_pct} + : JsonValue{}; + std::string status = "pass"; + if (recorded) { + status = "recorded"; + } else if (comparison.is_new) { + status = "new"; + } else if (comparison.regression && comparable) { + status = "regressed"; + } else if (!comparable) { + status = "not-compared"; + } + entry["status"] = JsonValue{status}; + entries.push_back(JsonValue{std::move(entry)}); + } + JsonValue::Object root; + root["schema_version"] = JsonValue{std::int64_t{1}}; + root["profile"] = JsonValue{prof_name}; + root["baseline"] = JsonValue{baseline_path.string()}; + root["recorded"] = JsonValue{recorded}; + root["comparable"] = JsonValue{comparable}; + root["benchmarks"] = JsonValue{std::move(entries)}; + root["regressions"] = JsonValue{regressions}; + JsonValue document; + document.value = std::move(root); + auto serialized = Void::Json::Strict::serialize(document); + if (!serialized) { + std::cerr << cmd_name << ": cannot serialize the benchmark results\n"; + all_ok = false; + } else if (auto written = Platform::atomic_write_file( + *opts.bench_json_arg, *serialized + '\n', false); + !written) { + std::cerr << cmd_name << ": cannot write '" << *opts.bench_json_arg + << "': " << written.error().message() << '\n'; + all_ok = false; + } + } + continue; + } + if (run_tests) { std::optional wine; if (windows_cross_target) { @@ -4606,7 +4869,7 @@ int execute_metadata_command(const MetadataCmdOptions &opts) { } JsonObject root; - root["schema_version"] = number(1); + root["schema_version"] = number(2); root["project_root"] = text(project_root.string()); root["build_root"] = text(build_root.string()); root["profile"] = text(desc->profile.name); @@ -6683,6 +6946,22 @@ 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 &bench_cmd = + root.subcommand("bench", "Build and run benchmark targets, enforcing timing regressions"); + configure_build_or_test(bench_cmd); + bench_cmd + .option("--baseline", "", + "Benchmark baseline file (default: /.vbs/bench_baseline.json)", + build_opts.bench_baseline_arg) + .option_default("--max-regression", "", + "Fail when a benchmark is slower by more than this percentage", + build_opts.bench_max_regression_arg, "5") + .option_default("--samples", "", "Measured runs per benchmark (1..100)", + build_opts.bench_samples_arg, "3") + .flag("--update-baseline", "", "Rewrite the baseline with the measured timings", + build_opts.bench_update_baseline) + .option("--json", "", "Write machine-readable benchmark results to this file", + build_opts.bench_json_arg); auto &run_cmd = root.subcommand("run", "Build and run an executable target"); configure_build_or_test(run_cmd); run_cmd.positional_many("args", "Arguments passed to the program (after --)", @@ -7531,10 +7810,15 @@ int main(int argc, char **argv) { : Void::Log::Level::Info); ConsoleLogGuard log_guard{log_level}; - if (cmd == "build" || cmd == "test" || cmd == "explain" || cmd == "run") { + if (cmd == "build" || cmd == "test" || cmd == "explain" || cmd == "run" || cmd == "bench") { const bool run_tests = cmd == "test"; + const bool run_benches = cmd == "bench"; build_opts.explain = cmd == "explain"; build_opts.run_after_build = cmd == "run"; + if (run_benches && build_opts.profiles.empty()) { + // Cargo-style: benchmarks run in the release profile unless one is selected. + build_opts.profiles.push_back("release"); + } if (build_opts.run_after_build && build_opts.profiles.size() > 1) { std::cerr << "vbs run: exactly one --profile may be selected\n"; return 2; @@ -7546,9 +7830,14 @@ int main(int argc, char **argv) { return 2; } if (Config::is_workspace_root(std::filesystem::path{build_opts.project_arg})) { + if (run_benches) { + std::cerr << "vbs bench: workspace roots are not supported yet; run it inside a " + "member\n"; + return 2; + } return execute_workspace(std::move(build_opts), run_tests); } - return execute_build_or_test(std::move(build_opts), run_tests); + return execute_build_or_test(std::move(build_opts), run_tests, run_benches); } if (cmd == "describe") { return execute_describe_command(describe_opts); diff --git a/tests/CliContracts.cmake b/tests/CliContracts.cmake index b562c09..41160e1 100644 --- a/tests/CliContracts.cmake +++ b/tests/CliContracts.cmake @@ -76,6 +76,11 @@ check_process(2 "" "at least one --source is required" fuzz) check_process(2 "" "invalid --runs value" fuzz --source f.cpp --runs 0) check_process(2 "" "--coverage-min and --coverage-diff require --coverage" test --coverage-min 80) check_process(2 "" "invalid --shard value" test --shard 0/2) +check_process(0 "Usage: vbs bench " "" bench --help) +check_process(0 "--max-regression" "" bench --help) +check_process(0 "--update-baseline" "" bench --help) +check_process(2 "" "invalid --max-regression" bench --max-regression abc) +check_process(2 "" "invalid --samples" bench --samples 0) check_process(2 "" "test-runner options require" build --rerun-failed) check_process(2 "" "invalid value 'bogus' for '--sandbox'" build --sandbox bogus) check_process(0 "Usage: vbs new " "" new --help) diff --git a/tests/FullV1Tests.cpp b/tests/FullV1Tests.cpp index 255eb54..b625f9f 100644 --- a/tests/FullV1Tests.cpp +++ b/tests/FullV1Tests.cpp @@ -5852,7 +5852,7 @@ VOID_TEST(FullV1Tests, json_schemas_validate_metadata_describe_and_explain) { Void::Testing::require(parsed.has_value()); return *parsed; }; - const auto metadata_schema = load_schema("metadata-v1.schema.json"); + const auto metadata_schema = load_schema("metadata-v2.schema.json"); const auto describe_schema = load_schema("describe-v1.schema.json"); const auto explain_schema = load_schema("explain-v1.schema.json"); @@ -5871,11 +5871,15 @@ void build(Void::Build::Project &p) { p.test("check") .cxx_standard(Void::Build::CxxStandard::Cxx26) .sources({"tests/check.cpp"}); + p.benchmark("bench") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"benches/bench.cpp"}); } )cpp"); write_file(proj / "src" / "demo.cpp", "int demo() { return 1; }\n"); write_file(proj / "src" / "main.cpp", "int demo();\nint main() { return demo() == 1 ? 0 : 1; }\n"); write_file(proj / "tests" / "check.cpp", "int main() { return 0; }\n"); + write_file(proj / "benches" / "bench.cpp", "int main() { return 0; }\n"); auto run_vbs = [&](std::vector args) { Platform::ProcessRequest req; @@ -5911,7 +5915,7 @@ void build(Void::Build::Project &p) { } Void::Testing::expect(valid); } - Void::Testing::expect_eq(schema_version(metadata_document), 1LL); + Void::Testing::expect_eq(schema_version(metadata_document), 2LL); auto describe = run_vbs({"describe", "--project", proj.string(), "--build-dir", (tmp / "build").string()}); @@ -5986,3 +5990,187 @@ void build(Void::Build::Project &p) { } } +// === G1/G8: benchmark targets, baselines and the regression gate === +VOID_TEST(FullV1Tests, bench_records_baseline_and_enforces_regression_gate) { + 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_bench_"}; + const auto proj = tmp / "proj"; + write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.benchmark("bench_sleep") + .cxx_standard(Void::Build::CxxStandard::Cxx26) + .sources({"benches/sleep.cpp"}); +} +)cpp"); + write_file(proj / "benches" / "sleep.cpp", R"cpp(#include +#include +int main() { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + return 0; +} +)cpp"); + auto run_vbs = [&](std::vector args) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = std::move(args); + req.timeout = std::chrono::seconds{600}; + return Platform::run_supervised(req); + }; + const auto build_dir = tmp / "build"; + auto bench = [&](std::vector extra) { + std::vector args{"bench", "--project", proj.string(), "--build-dir", + build_dir.string(), "-p", "debug", "--samples", "1"}; + args.insert(args.end(), extra.begin(), extra.end()); + return run_vbs(std::move(args)); + }; + const auto baseline_path = build_dir / ".vbs" / "bench_baseline.json"; + const auto parse_object = [](const std::string &text) { + auto parsed = Void::Json::Strict::parse(text); + Void::Testing::require(parsed.has_value()); + const auto *object = std::get_if(&parsed->value); + Void::Testing::require(object != nullptr); + return *object; + }; + const auto string_field = [](const JsonValue::Object &object, std::string_view key) { + const auto *value = std::get_if(&object.at(std::string{key}).value); + Void::Testing::require(value != nullptr); + return *value; + }; + + // First run: no baseline yet, so it is recorded and the run succeeds. + auto recorded = bench({}); + Void::Testing::expect(recorded.has_value() && recorded->succeeded()); + auto baseline_text = Void::FileSystem::read_file(baseline_path); + Void::Testing::require(baseline_text.has_value()); + const auto recorded_document = parse_object(*baseline_text); + const auto *version = std::get_if( + &recorded_document.at("schema_version").value); + Void::Testing::require(version != nullptr); + Void::Testing::expect_eq(*version, 1LL); + const auto *recorded_benchmarks = + std::get_if(&recorded_document.at("benchmarks").value); + Void::Testing::require(recorded_benchmarks != nullptr); + const auto *recorded_best = + std::get_if(&recorded_benchmarks->at("bench_sleep").value); + Void::Testing::require(recorded_best != nullptr); + Void::Testing::expect(*recorded_best > 0.0); + const std::string recorded_os = string_field(recorded_document, "os"); + const std::string recorded_arch = string_field(recorded_document, "architecture"); + const std::string recorded_compiler = string_field(recorded_document, "compiler"); + const std::string recorded_profile = string_field(recorded_document, "profile"); + + // A high threshold passes; a crafted low baseline fails the gate. + auto relaxed = bench({"--max-regression", "1000"}); + Void::Testing::expect(relaxed.has_value() && relaxed->succeeded()); + + const auto write_baseline = [&](double best, std::string os) { + JsonValue::Object benchmarks; + benchmarks["bench_sleep"] = JsonValue{best}; + JsonValue::Object root; + root["schema_version"] = JsonValue{std::int64_t{1}}; + root["os"] = JsonValue{std::move(os)}; + root["architecture"] = JsonValue{recorded_arch}; + root["compiler"] = JsonValue{recorded_compiler}; + root["profile"] = JsonValue{recorded_profile}; + root["benchmarks"] = JsonValue{std::move(benchmarks)}; + JsonValue document; + document.value = std::move(root); + auto serialized = Void::Json::Strict::serialize(document); + Void::Testing::require(serialized.has_value()); + write_file(baseline_path, *serialized + "\n"); + }; + write_baseline(1e-9, recorded_os); + auto regressed = bench({"--max-regression", "5"}); + Void::Testing::expect(regressed.has_value() && regressed->exit_code == 1); + if (regressed) { + const std::string output = regressed->stdout_data + regressed->stderr_data; + Void::Testing::expect(output.find("REGRESSED") != std::string::npos); + Void::Testing::expect(output.find("exceed --max-regression") != std::string::npos); + } + + // A generous baseline passes and --json writes the machine-readable result. + write_baseline(1e9, recorded_os); + const auto results_path = tmp / "bench-results.json"; + auto passing = bench({"--max-regression", "5", "--json", results_path.string()}); + Void::Testing::expect(passing.has_value() && passing->succeeded()); + auto results_text = Void::FileSystem::read_file(results_path); + Void::Testing::require(results_text.has_value()); + const auto results_document = parse_object(*results_text); + const auto *results_version = + std::get_if(&results_document.at("schema_version").value); + Void::Testing::require(results_version != nullptr); + Void::Testing::expect_eq(*results_version, 1LL); + const auto *results_entries = + std::get_if(&results_document.at("benchmarks").value); + Void::Testing::require(results_entries != nullptr); + Void::Testing::expect_eq(results_entries->size(), std::size_t{1}); + const auto *entry = std::get_if(&results_entries->front().value); + Void::Testing::require(entry != nullptr); + Void::Testing::expect_eq(string_field(*entry, "name"), std::string{"bench_sleep"}); + Void::Testing::expect_eq(string_field(*entry, "status"), std::string{"pass"}); + const auto *result_regressions = + std::get_if(&results_document.at("regressions").value); + Void::Testing::require(result_regressions != nullptr); + Void::Testing::expect_eq(*result_regressions, 0LL); + + // --update-baseline rewrites a failing baseline with the measured timing. + write_baseline(1e-9, recorded_os); + auto updated = bench({"--update-baseline"}); + Void::Testing::expect(updated.has_value() && updated->succeeded()); + auto updated_text = Void::FileSystem::read_file(baseline_path); + Void::Testing::require(updated_text.has_value()); + const auto updated_document = parse_object(*updated_text); + const auto *updated_benchmarks = + std::get_if(&updated_document.at("benchmarks").value); + Void::Testing::require(updated_benchmarks != nullptr); + const auto *updated_best = + std::get_if(&updated_benchmarks->at("bench_sleep").value); + Void::Testing::require(updated_best != nullptr); + Void::Testing::expect(*updated_best > 0.5); + + // Baselines from another machine are not comparable: warn but do not fail. + write_baseline(1e-9, "Windows"); + auto mismatched = bench({"--max-regression", "5"}); + Void::Testing::expect(mismatched.has_value() && mismatched->succeeded()); + if (mismatched) { + Void::Testing::expect((mismatched->stdout_data + mismatched->stderr_data) + .find("skipping the regression gate") != std::string::npos); + } + + // Without benchmark targets the command is a usage error. + const auto plain = tmp / "plain"; + write_file(plain / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { p.executable("app").sources({"src/main.cpp"}); } +)cpp"); + write_file(plain / "src" / "main.cpp", "int main() { return 0; }\n"); + auto none = run_vbs({"bench", "--project", plain.string(), "--build-dir", + (tmp / "build-plain").string(), "-p", "debug"}); + Void::Testing::expect(none.has_value() && none->exit_code == 2); + if (none) { + Void::Testing::expect(none->stderr_data.find("no benchmark targets") != std::string::npos); + } + + // Invalid thresholds are rejected before any build work. + auto bad_threshold = + run_vbs({"bench", "--project", proj.string(), "--build-dir", build_dir.string(), + "--max-regression", "abc"}); + Void::Testing::expect(bad_threshold.has_value() && bad_threshold->exit_code == 2); + if (bad_threshold) { + Void::Testing::expect(bad_threshold->stderr_data.find("invalid --max-regression") != + std::string::npos); + } + auto bad_samples = + run_vbs({"bench", "--project", proj.string(), "--build-dir", build_dir.string(), + "--samples", "0"}); + Void::Testing::expect(bad_samples.has_value() && bad_samples->exit_code == 2); + if (bad_samples) { + Void::Testing::expect(bad_samples->stderr_data.find("invalid --samples") != + std::string::npos); + } +} + +