diff --git a/CMakeLists.txt b/CMakeLists.txt index f269d4f..301e809 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,6 +41,7 @@ add_library(VoidBuild_Core STATIC src/Toolchain/Driver.cpp src/Snapshot/Snapshot.cpp src/State/StateStore.cpp + src/State/RemoteCache.cpp src/Graph/Graph.cpp src/Execution/Scheduler.cpp src/Config/Frontend.cpp diff --git a/README.md b/README.md index b096f3b..dadadff 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,22 @@ dev cpp-gcc -c cmake -S . -B build/dev-local -G Ninja \ -DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=../VoidLibrary ``` +### Docker build & test (GCC 16) + +The VoidLibrary development image provides GCC 16 with C++26 reflection, CMake 4 and Ninja. +Mount this repository and run the bootstrap build and tests inside it: + +```sh +docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD":/src -w /src \ + voidlibrary-dev:latest bash -lc ' + cmake -S . -B build/docker -G Ninja -DCMAKE_BUILD_TYPE=Debug && + cmake --build build/docker --parallel 4 && + ctest --test-dir build/docker --output-on-failure' +``` + +To build against a local VoidLibrary checkout instead of fetching the pinned revision, add +`-DVBS_VOID_SOURCE_DIR=/path/to/VoidLibrary` and mount that checkout into the container. + ### Self-building and self-testing VoidBuildSystem with `vbs` Once the bootstrap `vbs` binary is built, `VoidBuildSystem` builds `VoidLibrary` and tests all binaries and full `VOID_TEST` suites directly from root [build.cpp](build.cpp) with zero CMake invocation and live progress logs (`-v`/`--verbose` for debug detail, `-q`/`--quiet` for warnings/errors only): @@ -73,7 +89,7 @@ All CLI help text (`vbs --help`, `vbs --help`, `vbs compdb --help`, `v - `vbs [--version] [--verbose] [--quiet] ` - `vbs init [--dir DIR] [--name NAME] [--library] [--with-toml] [--force]` -- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--locked] [--offline] [--no-cache] [--native-foreign] [--verbose] [--quiet]` +- `vbs build [--project DIR] [--build-dir DIR] [--profile NAME]... [--target NAME]... [--compiler gcc|clang] [--editor-profile NAME] [--build-source FILE]... [--jobs N] [--remote-cache URL] [--remote-cache-token-env VAR] [--locked] [--offline] [--no-cache] [--native-foreign] [--verbose] [--quiet]` - `vbs test ...` (same flags as `vbs build`, then runs selected `TargetKind::Test` binaries) - `vbs clean [--build-dir DIR] [--all]` - `vbs doctor` diff --git a/build.cpp b/build.cpp index 5417430..3034e3d 100644 --- a/build.cpp +++ b/build.cpp @@ -29,6 +29,7 @@ void build(Void::Build::Project &project) { "src/Toolchain/Driver.cpp", "src/Snapshot/Snapshot.cpp", "src/State/StateStore.cpp", + "src/State/RemoteCache.cpp", "src/Graph/Graph.cpp", "src/Execution/Scheduler.cpp", "src/Config/Frontend.cpp", diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 7cfa92f..8b679cc 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,8 @@ # Development state -Updated: 2026-11-27 +Updated: 2026-12-03 Branch: main -Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration complete +Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B1–B3) + Track E1 + `vbs ide` & `build.cpp` CompDB integration + Track D1/D2 (Docker GCC 16) complete ## Completed delivery waves @@ -54,9 +54,14 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Track B3 (Foreign CMake C++20 `CXX_MODULES` & NixOS `clang-scan-deps` Include Discovery)**: Populated `ToolchainCapabilities::default_include_dirs` from Clang `-E -v` so NixOS `clang-scan-deps` resolves standard library headers; added `external_module_bmis` + `ImportedTargetInterface::module_bmis` propagation in `ModuleScanner.{hpp,cpp}`, `Graph.{hpp,cpp}`, `Provider.cpp`, and `Translator.cpp`; lowered CMake `CXX_MODULES` `fileSets` natively on both GCC 16 and Clang 23, including VBS targets importing modules exported by translated CMake libraries. - **IDE Integration (`build.cpp` CompDB & `vbs ide generate|query`)**: Added `project_build_descriptor_commands` indexing `build.cpp`/`build.profiles.cpp`/`build-support/` with `` include paths in `compile_commands.json`; implemented `vbs ide generate` (non-destructive `.clangd` with GCC flag stripping, `.vscode/{tasks,launch,settings}.json`, `.zed/{tasks,debug}.json`, `.idea/customTargets.xml`) and `vbs ide query` workspace/target JSON output in `CompDb.{hpp,cpp}`, `Watcher.cpp`, `Main.cpp`, `tests/CliContracts.cmake`, and `tests/FullV1Tests.cpp`. +- **Wave 11 (Track D1–D2 Shared HTTP Action Cache & Parallel Snapshot Hashing)**: + - **D1**: Added `include/Void/Build/State/RemoteCache.hpp` + `src/State/RemoteCache.cpp` (bearer-authenticated HTTP CAS client with SHA-256 verification on every read), `StateStore` remote action/blob APIs, `/api/v1/cas/{blobs,actions}` endpoints with RBAC/audit in `vbs-registry`, build-path-independent remote action keys and normalized records in `Scheduler.cpp`, and `vbs build|test --remote-cache` / `--remote-cache-token-env` (plus `VBS_REMOTE_CACHE` / `VBS_REMOTE_CACHE_TOKEN`). + - **D2**: Snapshot capture revalidation now hashes on a bounded `Void::Concurrency::ThreadPool` for trees of 32+ files. + - **Docker verification**: built and tested in `voidlibrary-dev` (GCC 16.0.1, pinned VoidLibrary `3e25405`) with `8/8` CTest suites passing. D1 acceptance verified end-to-end: a cold `vbs build` populates the remote CAS, and a second clean build directory reports `0 executed` with the binary running. D2 benchmark on 5,001 files: `warm_noop_ms=374` (5,002 cached, 0 executed), meeting the sub-second gate. Also fixed the self-host recipe source list for `RemoteCache.cpp` and accepted GCC 16's `-lgcc_s_asneeded` system link flag. + ## Remaining future scope -- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D (shared HTTP CAS + parallel hashing + SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. +- **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D1/D2 acceptance scenarios (suites pass; cache-hit/benchmark pending), Track D3 (SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. ## Environment notes & upstream boundaries diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 9b3a4e7..1414227 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -1,6 +1,6 @@ # Task graph and ownership -Updated: 2026-11-27 +Updated: 2026-12-03 Base HEAD: `fe0d1a6` | Wave | Scope | Status | Primary Deliverables | @@ -17,4 +17,5 @@ Base HEAD: `fe0d1a6` | Wave 8 (Plan 20 Slice 2A Meson Native Translation, Everyday DX CLI, & Expansion Roadmap) | Bounded Meson `intro-targets.json` + `build.ninja` native translation & unified `resolve_foreign_with_translation`; `vbs build\|test --native-foreign`, `vbs init`, `vbs clean`, `vbs doctor`, `vbs graph`; 5-track post-v1 expansion roadmap | COMPLETE & VERIFIED | `include/Void/Build/Provider/Translator.hpp`, `src/Provider/Translator.cpp`, `src/Main.cpp`, `tests/FullV1Tests.cpp`, `tests/CliContracts.cmake`, `docs/roadmap/21-expansion-roadmap.md`, updated docs | | Wave 9 (Track A — Zero-CMake Self-Hosting, Full `VOID_TEST` Suite, & Bit-Identical Stage 2 == Stage 3) | First-class `builder == "native"` provider + `.native_builder()` in `build.cpp`; all tests migrated to `VOID_TEST(Suite, name)` & `VoidTestScanner.cmake` removed; all 13 targets (`vbs_benchmarks` + 6 test suites) declared in `build.cpp`; `binary_dir = ""` + `/vbs-build` prefix map + `-frandom-seed` Stage 2 == Stage 3 reproducibility verified with trapped `cmake` | COMPLETE & VERIFIED | `include/Void/Build/Provider/Provider.hpp`, `src/Provider/Provider.cpp`, `src/Graph/Graph.cpp`, `src/Toolchain/Driver.cpp`, `src/Main.cpp`, `recipes/VoidLibrary/VoidLibraryRecipe.{hpp,cpp}`, `build.cpp`, `CMakeLists.txt`, `tests/*`, docs | | Wave 10 (Track B [B1–B3] + First-Class `vbs ide` Integration) | Native C driver (`CStandard`) & mixed C/C++ CMake/Meson translation (`PerFileOption`); bounded `build.ninja` `CUSTOM_COMMAND` translation (`CustomAction`); foreign CMake `CXX_MODULES` `fileSets` & cross-target `module_bmis` + Clang `default_include_dirs`; `build.cpp` SDK CompDB indexing + `vbs ide generate\|query` | COMPLETE & VERIFIED | `include/Void/Build.hpp`, `Driver.{hpp,cpp}`, `ModuleScanner.{hpp,cpp}`, `Graph.{hpp,cpp}`, `CompDb.{hpp,cpp}`, `Provider.cpp`, `Translator.{hpp,cpp}`, `Watcher.cpp`, `Main.cpp`, `tests/{FullV1Tests.cpp,CliContracts.cmake}`, docs | +| Wave 11 (Track D1–D2) | Shared HTTP CAS action cache (`/api/v1/cas/{blobs,actions}`, bearer auth, digest verification, portable action keys, `--remote-cache`) + parallel snapshot revalidation hashing | COMPLETE & VERIFIED (Docker GCC 16.0.1, pinned VoidLibrary, 8/8 CTest suites; D1 cross-build-dir 100% cache hit; D2 5,001-file warm no-op 374 ms) | `include/Void/Build/State/RemoteCache.hpp`, `src/State/RemoteCache.cpp`, `StateStore.{hpp,cpp}`, `Scheduler.cpp`, `Snapshot.cpp`, `registry/service/RegistryService.cpp`, `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | | Future (Plan 20 Slice 3 / Tracks C–D, E2, E3 daemon, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; shared HTTP CAS & SBOM/signatures; `workspace.cpp`, `vbs daemon`, `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 1c8413f..3e0e346 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -100,10 +100,66 @@ dev cpp-gcc -c build/dev/bin/vbs_benchmarks --files 15 {"fixture_files":16,"compiler":"g++ (GCC) 16.2.0","snapshot_ms":19,"cold_build_ms":334,"cold_executed":17,"warm_noop_ms":4,"warm_executed":0,"warm_cached":17} ``` +## Track D1/D2 Verification in Docker (2026-12-03) + +The host shell lacks `dev`/GCC 16, so the build and tests were run inside the existing +`voidlibrary-dev:latest` Docker image (GCC 16.0.1, CMake 4.2.3, Ninja 1.11.1). CMake fetched +the exact pinned VoidLibrary commit `3e254055e081a104f08df68dde39711bc7813518` inside the +container (network access works there). + +```sh +docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD":/src -w /src \ + voidlibrary-dev:latest bash -lc ' + cmake -S . -B build/docker-pinned -G Ninja -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON && + cmake --build build/docker-pinned --parallel 4 && + ctest --test-dir build/docker-pinned --output-on-failure' +``` + +- Configure: exit `0` (`VoidLibrary` cloned at pinned commit `3e25405`). +- Build: `170/170` targets linked (warnings only from dependency headers / aggregate + initialization). +- `ctest`: **8 / 8 passed (100%)** in 374.33 s on the final run: + `vbs_sdk_tests`, `vbs_core_tests` (20.19 s), `vbs_v1_tests` (42.65 s), + `vbs_registry_tests` (11.36 s, includes the remote-CAS round-trip and the D1 acceptance), + `vbs_selfhost_tests` (299.69 s), `vbs_sdk_registration`, `vbs_cli_contract`, + `vbs_description_contract`. + +Two pre-existing Docker-toolchain failures were found and fixed during this run: + +1. `recipes/SelfHost/VbsSelfHostRecipe.cpp` did not list the new `src/State/RemoteCache.cpp`, + so the native Stage 1 self-host link failed; adding it fixed + `strict_native_full_vbs_stage1_to_stage2_without_cmake`. +2. GCC 16's CMake emits `-lgcc_s_asneeded` (a real as-needed linker script for `libgcc_s`) + in codemodel link fragments. It is now accepted as a safe system link flag in + `src/Provider/Translator.cpp`, fixing + `track_b1_native_c_driver_and_mixed_c_cpp_cmake_meson_translation`. + +### D1 acceptance (cross-build-directory 100% cache hit) + +`RegistryTests.shared_remote_cache_cold_populates_then_clean_build_all_hits` runs a real +`vbs build` into `build_a` (populating the remote CAS through the live registry), then a +second `vbs build` into a clean `build_b`: the summary reports `0 executed` (all actions +restored from the shared cache), and the produced binary runs successfully. + +### D2 5,000-file benchmark + +```sh +docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$PWD":/src -w /src \ + voidlibrary-dev:latest bash -lc './build/docker-pinned/bin/vbs_benchmarks --files 5000 --jobs 8' +``` + +```json +{"fixture_files":5001,"compiler":"g++ 16.0.1","snapshot_ms":3997,"cold_build_ms":1270353,"cold_executed":5002,"warm_noop_ms":374,"warm_executed":0,"warm_cached":5002} +``` + +Warm no-op is **374 ms for 5,001 files** (all 5,002 actions cached, zero executed), meeting +the sub-second D2 acceptance gate. + ## Limits and Unrun Checks -1. **HTTPS git fetch in proxy-restricted environment**: Inside this execution environment, outbound HTTPS to `https://git.faumaray.com/Void/VoidLibrary.git` encountered `Proxy CONNECT aborted`; CMake configure and `vbs test` were therefore verified against a clean local detached checkout of the exact pinned commit `3e254055e081a104f08df68dde39711bc7813518` via `VBS_VOID_SOURCE_DIR`. +1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). 2. **Conan2 live installation**: `conan` is absent in `dev cpp-gcc`; automated testing verified explicit missing-prerequisite failure (`FullV1Tests.cpp`). Live `conan` container verification (Track B3) remains unrun. 3. **Optional external VoidLibrary modules (`Void::Net`, `Void::Sqlite`)**: `Boost`, `OpenSSL`, and `SQLite3` are not installed in `dev cpp-gcc`, so VBS continues using its pure-C++/POSIX loopback HTTP adapters (`HttpServer`, `RegistryClient`) and journaled atomic CAS store (`StateStore`), while retaining optional `Void::Sqlite` CMake detection. 4. **CI workflow & Web UI browser**: [.github/workflows/ci.yml](../../.github/workflows/ci.yml) has not been executed on remote GitHub Actions runners, and `registry/web/` was verified via HTTP/header/static-serving/API/XSS/CSRF tests without a headless browser runner. -5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D (shared HTTP CAS, parallel hashing, SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. +5. **Remaining Post-v1 Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` container verification, Track C (Windows/MSVC, macOS/Apple Clang, dual-profile cross-compilation), Track D1/D2 acceptance scenarios (unit/integration suites pass in Docker; see above), Track D3 (SBOM/signatures), Track E2 (`workspace.cpp`), Track E3 (`vbs daemon` local socket server + external editor plugins), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index a3dec69..69312bd 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -1,6 +1,6 @@ # 21 — Post-v1 Expansion Roadmap -Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track C**, **Track D**, **Track E2 (`workspace.cpp`)**, **Track E3 (`vbs daemon`)**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). +Status: Active execution guide (Plans **01–19**, **Plan 20 Slices 1–2C**, **Track A [A1–A3]**, **Track B [B1–B3, except live `conan` CLI container]**, **Track E1**, and **Track E3 IDE config/query tooling** are implemented and verified; **Track D1/D2** are implemented and verified in Docker GCC 16 (D1 cross-build-directory 100% cache hit; D2 5,001-file warm no-op 374 ms); **Track C**, **Track D3**, **Track E2 (`workspace.cpp`)**, **Track E3 (`vbs daemon`)**, **Track E4**, and live `conan` CLI verification remain planned; see [STATE](../agent-workflow/STATE.md) and [VERIFICATION](../agent-workflow/VERIFICATION.md)). This roadmap defines five orthogonal expansion tracks for taking VoidBuildSystem from a verified self-hosting Linux C++26 build system into a multi-platform, distributed, daily-driver ecosystem. Each track preserves core architectural invariants: ordinary C++ descriptions, hermetic content-verified snapshots, isolated profiles, immutable CAS publication, and explicit diagnostics over silent approximation. @@ -59,8 +59,8 @@ flowchart LR | Phase | Concrete Scope | Acceptance Gate | | --- | --- | --- | -| **D1 — Shared HTTP Content-Addressed Action Cache (CAS)** | Push/pull action records and output blobs (`PUT/GET /v1/cas/blobs/{sha256}`, `/v1/cas/actions/{action_key}`) against `vbs-registry` or any compatible HTTP CAS server with bearer auth and digest verification on every read. | Cold CI build populates remote CAS; second clean machine achieves 100% cache hit with verified SHA-256 outputs. | -| **D2 — Fast Hashing & Parallel Snapshot Pipeline** | Adopt `Void::Crypto` BLAKE2b / hardware-accelerated SHA-256 (when available) + parallel snapshot hashing across `Void::Concurrency::ThreadPool` + optional `Void::Sqlite` indexed state store for >10k-file monorepos. | Sub-second warm no-op on 5,000-file synthetic benchmark fixture (`vbs_benchmarks`). | +| **D1 — Shared HTTP Content-Addressed Action Cache (CAS)** *(verified: cross-build-directory 100% cache hit)* | Push/pull action records and output blobs (`PUT/GET /api/v1/cas/blobs/{sha256}`, `/api/v1/cas/actions/{action_key}`) against `vbs-registry` or any compatible HTTP CAS server with bearer auth and digest verification on every read. Action keys are normalized to be build-directory independent; `vbs build/test --remote-cache URL [--remote-cache-token-env VAR]` (or `VBS_REMOTE_CACHE` / `VBS_REMOTE_CACHE_TOKEN`). | Cold CI build populates remote CAS; second clean machine achieves 100% cache hit with verified SHA-256 outputs. | +| **D2 — Fast Hashing & Parallel Snapshot Pipeline** *(verified: 5,001-file warm no-op 374 ms)* | Adopt `Void::Crypto` BLAKE2b / hardware-accelerated SHA-256 (when available) + parallel snapshot hashing across `Void::Concurrency::ThreadPool` + optional `Void::Sqlite` indexed state store for >10k-file monorepos. Snapshot capture revalidation now hashes on a bounded thread pool for trees of 32+ files. | Sub-second warm no-op on 5,000-file synthetic benchmark fixture (`vbs_benchmarks`). | | **D3 — Supply-Chain Provenance & Signed Packages** | Emit SPDX/CycloneDX SBOM JSON from `vbs.lock` + `BuildGraph`; optional Ed25519 package & binary signature verification in `vbs publish` and `vbs build --locked`. | Tampered archive or signature fails closed before extraction. | --- diff --git a/include/Void/Build/State/RemoteCache.hpp b/include/Void/Build/State/RemoteCache.hpp new file mode 100644 index 0000000..7008e15 --- /dev/null +++ b/include/Void/Build/State/RemoteCache.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Build::State { + +// Runtime-only remote cache endpoint. The bearer token is never persisted, logged or +// embedded in action records; callers read it from the environment. +struct RemoteCacheConfig { + std::string url; // http(s)://host:port[/base-path] + std::string bearer_token; // Runtime-only authentication secret. +}; + +// Small HTTP client for the shared content-addressed action cache (Track D1). +// Blobs are addressed by their SHA-256 content digest and are always re-verified on read; +// action records are addressed by a build-path-independent action key. +class RemoteCasClient { + public: + explicit RemoteCasClient(RemoteCacheConfig config); + + [[nodiscard]] const RemoteCacheConfig &config() const noexcept { return config_; } + [[nodiscard]] bool configured() const noexcept { return !config_.url.empty(); } + + // PUT /api/v1/cas/blobs/ with the exact blob bytes. + [[nodiscard]] Void::Result::Result + put_blob(std::string_view sha256, std::string_view bytes) const; + + // GET /api/v1/cas/blobs/; the returned bytes are SHA-256 verified before use. + [[nodiscard]] Void::Result::Result, Void::Result::Error> + get_blob(std::string_view sha256) const; + + // PUT /api/v1/cas/actions/ with a UTF-8 JSON action record. + [[nodiscard]] Void::Result::Result + put_action(std::string_view action_key, std::string_view json) const; + + // GET /api/v1/cas/actions/; std::nullopt on 404. + [[nodiscard]] Void::Result::Result, Void::Result::Error> + get_action(std::string_view action_key) const; + + private: + RemoteCacheConfig config_; +}; + +} // namespace Void::Build::State diff --git a/include/Void/Build/State/StateStore.hpp b/include/Void/Build/State/StateStore.hpp index f01524d..697e434 100644 --- a/include/Void/Build/State/StateStore.hpp +++ b/include/Void/Build/State/StateStore.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -99,6 +100,21 @@ class StateStore { [[nodiscard]] Void::Result::Result, Void::Result::Error> list_generations(std::optional profile_name = std::nullopt) const; + // Shared HTTP content-addressed action cache (Track D1). Configuration is runtime-only; + // the bearer token is never persisted. Remote reads always re-verify SHA-256 digests. + void configure_remote_cache(std::optional config); + [[nodiscard]] bool has_remote_cache() const noexcept { return remote_.has_value(); } + + [[nodiscard]] Void::Result::Result, Void::Result::Error> + fetch_remote_action(std::string_view action_key) const; + [[nodiscard]] Void::Result::Result + publish_remote_action(std::string_view action_key, std::string_view json) const; + // Ensures a remote blob is present in the local CAS (downloading + verifying if needed). + [[nodiscard]] Void::Result::Result + ensure_remote_blob(std::string_view sha256); + [[nodiscard]] Void::Result::Result + publish_remote_blob(std::string_view sha256) const; + // Leases protect active runs from GC deletion. [[nodiscard]] Void::Result::Result acquire_lease(std::string_view profile_name, const std::set &pinned_blobs = {}); @@ -137,6 +153,7 @@ class StateStore { std::filesystem::path db_file_; std::filesystem::path lock_file_; std::shared_ptr cache_; + std::optional remote_; }; } // namespace Void::Build::State diff --git a/recipes/SelfHost/VbsSelfHostRecipe.cpp b/recipes/SelfHost/VbsSelfHostRecipe.cpp index 03e5b64..9d0780a 100644 --- a/recipes/SelfHost/VbsSelfHostRecipe.cpp +++ b/recipes/SelfHost/VbsSelfHostRecipe.cpp @@ -81,6 +81,7 @@ add_vbs_selfhost_native(Project &project, const VbsSelfHostConfig &config) { "src/Toolchain/Driver.cpp", "src/Snapshot/Snapshot.cpp", "src/State/StateStore.cpp", + "src/State/RemoteCache.cpp", "src/Graph/Graph.cpp", "src/Execution/Scheduler.cpp", "src/Config/Frontend.cpp", diff --git a/registry/include/Void/Build/Registry/RegistryService.hpp b/registry/include/Void/Build/Registry/RegistryService.hpp index c656a2e..6c06ec0 100644 --- a/registry/include/Void/Build/Registry/RegistryService.hpp +++ b/registry/include/Void/Build/Registry/RegistryService.hpp @@ -135,6 +135,8 @@ class RegistryService { RegistryConfig config_; std::filesystem::path blobs_dir_; + std::filesystem::path action_blobs_dir_; + std::filesystem::path action_records_dir_; std::filesystem::path meta_file_; std::filesystem::path lock_file_; mutable std::mutex mu_; diff --git a/registry/service/RegistryService.cpp b/registry/service/RegistryService.cpp index ea84427..d541ef2 100644 --- a/registry/service/RegistryService.cpp +++ b/registry/service/RegistryService.cpp @@ -86,6 +86,14 @@ bool valid_package_name(std::string_view name) { }); } +bool is_sha256_hex(std::string_view hex) { + if (hex.size() != 64) { + return false; + } + return std::ranges::all_of( + hex, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }); +} + std::vector split_path(std::string_view path) { std::vector segs; for (const auto part : Void::Str::split(path, '/')) { @@ -144,6 +152,8 @@ std::string content_type_for_ext(const std::filesystem::path &p) { RegistryService::RegistryService(RegistryConfig config) : config_{std::move(config)}, blobs_dir_{config_.data_dir / "cas" / "blobs"}, + action_blobs_dir_{config_.data_dir / "action-cache" / "blobs"}, + action_records_dir_{config_.data_dir / "action-cache" / "actions"}, meta_file_{config_.data_dir / "metadata.v1.json"}, lock_file_{config_.data_dir / "registry.lock"} {} @@ -151,6 +161,8 @@ Void::Result::Result, Void::Result::Error> RegistryService::open(RegistryConfig config) { std::error_code ec; std::filesystem::create_directories(config.data_dir / "cas" / "blobs", ec); + std::filesystem::create_directories(config.data_dir / "action-cache" / "blobs", ec); + std::filesystem::create_directories(config.data_dir / "action-cache" / "actions", ec); if (ec) { return std::unexpected{make_error(Void::System::map_errno_to_system_code(ec.value()), "RegistryService::open: cannot create data directories")}; @@ -638,6 +650,66 @@ HttpResponse RegistryService::handle_request(const HttpRequest &req) { "}\n"); } + // Shared content-addressed action cache (Track D1). + // GET/PUT /api/v1/cas/blobs/ and /api/v1/cas/actions/. + if (segs.size() == 5 && segs[0] == "api" && segs[1] == "v1" && segs[2] == "cas" && + (segs[3] == "blobs" || segs[3] == "actions")) { + const bool is_blob = segs[3] == "blobs"; + const std::string &key = segs[4]; + if (!is_sha256_hex(key)) { + return HttpResponse::error_json(400, "invalid_key", + "CAS key must be a SHA-256 hex digest"); + } + if (!principal) { + return HttpResponse::error_json(401, "unauthorized", "authentication required"); + } + const auto base_dir = is_blob ? action_blobs_dir_ : action_records_dir_; + const auto resource_path = base_dir / key.substr(0, 2) / (is_blob ? key : key + ".json"); + + if (req.method == "GET") { + auto bytes = Void::FileSystem::read_file(resource_path); + if (!bytes) { + return HttpResponse::error_json(404, "not_found", "CAS object not found"); + } + HttpResponse resp; + resp.status = 200; + resp.headers["Content-Type"] = + is_blob ? "application/octet-stream" : "application/json; charset=utf-8"; + resp.body = std::move(*bytes); + return resp; + } + if (req.method != "PUT") { + return HttpResponse::error_json(405, "method_not_allowed", "CAS supports GET and PUT"); + } + if (!principal->scopes.contains("publish") && principal->role != Role::Admin) { + append_audit_locked(principal->username, "cas.put", key, "denied", + "missing publish scope"); + return HttpResponse::error_json(403, "forbidden", "publish scope required"); + } + if (!is_blob && !Void::Json::Strict::parse(req.body)) { + return HttpResponse::error_json(400, "invalid_json", "CAS action record must be JSON"); + } + if (is_blob && Util::sha256_hex(req.body) != key) { + append_audit_locked(principal->username, "cas.put", key, "denied", + "blob digest mismatch"); + return HttpResponse::error_json(400, "digest_mismatch", + "body SHA-256 does not match CAS key"); + } + std::error_code cas_ec; + if (std::filesystem::is_regular_file(resource_path, cas_ec)) { + return HttpResponse::json(200, "{\"stored\":true,\"created\":false}\n"); + } + std::filesystem::create_directories(resource_path.parent_path(), cas_ec); + auto wrote = + Platform::atomic_write_file(resource_path, req.body, true, is_blob ? 0444u : 0644u); + if (!wrote) { + return HttpResponse::error_json(500, "storage_error", "failed storing CAS object"); + } + append_audit_locked(principal->username, is_blob ? "cas.blob.put" : "cas.action.put", key, + "ok", "stored"); + return HttpResponse::json(201, "{\"stored\":true,\"created\":true}\n"); + } + auto can_read_pkg = [&](const PackageMeta &p) { if (!p.is_private) return true; diff --git a/src/Execution/Scheduler.cpp b/src/Execution/Scheduler.cpp index 99b1123..607d88f 100644 --- a/src/Execution/Scheduler.cpp +++ b/src/Execution/Scheduler.cpp @@ -3,7 +3,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -126,6 +128,256 @@ bool restore_outputs_from_cache(const Graph::ActionNode &action, return true; } +// Build-path-independent path mapping used for shared remote cache keys and records. +// Longest prefix wins so nested build/root prefixes are replaced before their parents. +struct PathMapper { + std::vector> pairs; + + [[nodiscard]] std::string normalize(std::string_view input) const { + std::string out{input}; + for (const auto &[prefix, token] : pairs) { + std::size_t pos = 0; + while ((pos = out.find(prefix, pos)) != std::string::npos) { + out.replace(pos, prefix.size(), token); + pos += token.size(); + } + } + return out; + } + + [[nodiscard]] std::string denormalize(std::string_view input) const { + std::string out{input}; + for (const auto &[prefix, token] : pairs) { + std::size_t pos = 0; + while ((pos = out.find(token, pos)) != std::string::npos) { + out.replace(pos, token.size(), prefix); + pos += prefix.size(); + } + } + return out; + } +}; + +PathMapper make_path_mapper(const Graph::BuildGraph &graph) { + std::vector> pairs; + auto add = [&](const std::filesystem::path &path, std::string token) { + if (!path.empty()) { + pairs.emplace_back(path.lexically_normal().string(), std::move(token)); + } + }; + add(graph.snapshot_materialized_root, "${SNAPSHOT}"); + add(graph.profile_build_dir, "${PROFILE}"); + if (!graph.profile_build_dir.empty()) { + // The whole build root (probes, .vbs state, other profiles) must stay portable too. + add(graph.profile_build_dir.parent_path().parent_path(), "${BUILD}"); + } + add(graph.project_root, "${PROJECT}"); + std::ranges::sort(pairs, + [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); }); + return PathMapper{std::move(pairs)}; +} + +std::string portable_executable(const std::filesystem::path &exe, const PathMapper &mapper) { + const std::string raw = exe.string(); + const std::string normalized = mapper.normalize(raw); + if (normalized == raw && exe.has_filename()) { + // Toolchain identity already covers the compiler; keep external tool paths portable. + return exe.filename().string(); + } + return normalized; +} + +// Portable action identity: logical action id + flags + input content digests, with all +// build-root/project-root prefixes normalized away. Absolute output paths are excluded. +std::string compute_remote_action_key(const Graph::ActionNode &action, + const Graph::BuildGraph &graph, RunDigestCache &digest_cache, + const PathMapper &mapper) { + Util::Sha256Hasher hasher; + hasher.update_length_prefixed("vbs-remote-action-v1"); + hasher.update_length_prefixed(graph.profile_identity); + hasher.update_length_prefixed(graph.toolchain.identity_hash); + hasher.update_length_prefixed(action.id); + hasher.update_u64(static_cast(action.kind)); + hasher.update_length_prefixed(portable_executable(action.executable, mapper)); + hasher.update_u64(action.arguments.size()); + for (const auto &arg : action.arguments) { + hasher.update_length_prefixed(mapper.normalize(arg)); + } + hasher.update_length_prefixed(mapper.normalize(action.response_file_content)); + hasher.update_u64(action.environment.size()); + for (const auto &[k, v] : action.environment) { + hasher.update_length_prefixed(k); + hasher.update_length_prefixed(mapper.normalize(v)); + } + hasher.update_u64(action.declared_inputs.size()); + for (const auto &in : action.declared_inputs) { + hasher.update_length_prefixed(mapper.normalize(in.string())); + if (auto digest = digest_cache.hash_file(in); digest) { + hasher.update_length_prefixed(*digest); + } else { + hasher.update_length_prefixed(""); + } + } + hasher.update_u64(action.nondeterministic ? 1u : 0u); + return hasher.finalize_hex(); +} + +std::string serialize_remote_record(const State::ActionSuccessRecord &record, + const Graph::ActionNode &action, const PathMapper &mapper, + std::string_view remote_key) { + using Util::json_array; + using Util::json_quote; + + std::vector ordered_outputs; + ordered_outputs.reserve(action.declared_outputs.size()); + for (const auto &out : action.declared_outputs) { + const auto it = record.outputs.find(out.string()); + if (it == record.outputs.end()) { + return {}; + } + ordered_outputs.push_back(it->second); + } + + std::string json = "{\"schema_version\":1,\"action_key\":" + json_quote(remote_key) + + ",\"profile_identity\":" + json_quote(record.profile_identity) + + ",\"target_name\":" + json_quote(record.target_name) + + ",\"recorded_epoch\":" + std::to_string(record.recorded_epoch) + + ",\"outputs\":"; + json += json_array(ordered_outputs, [](const State::BlobRef &ref) { + return "{\"sha256\":" + json_quote(ref.sha256) + ",\"size\":" + std::to_string(ref.size) + + ",\"mode\":" + std::to_string(ref.mode) + '}'; + }); + json += ",\"discovered_inputs\":["; + bool first = true; + for (const auto &[path, digest] : record.discovered_inputs) { + if (!first) { + json += ','; + } + first = false; + json += "{\"path\":" + json_quote(mapper.normalize(path)) + + ",\"sha256\":" + json_quote(digest) + '}'; + } + json += "],\"lookup_guards\":"; + json += json_array(record.lookup_guards, [&](const Snapshot::LookupGuard &guard) { + std::vector roots; + roots.reserve(guard.search_roots.size()); + for (const auto &root : guard.search_roots) { + roots.push_back(mapper.normalize(root)); + } + return "{\"search_roots\":" + json_array(roots, json_quote) + + ",\"lookup_name\":" + json_quote(guard.lookup_name) + + ",\"matched_root_index\":" + std::to_string(guard.matched_root_index) + + ",\"matched_sha256\":" + json_quote(guard.matched_sha256) + '}'; + }); + json += '}'; + return json; +} + +using RemoteJson = Void::Json::Strict::Value; + +const RemoteJson *remote_find(const RemoteJson::Object &obj, const std::string &key) { + const auto it = obj.find(key); + return it == obj.end() ? nullptr : &it->second; +} + +std::string remote_str(const RemoteJson::Object &obj, const std::string &key) { + const auto *value = remote_find(obj, key); + if (!value) { + return {}; + } + const auto *text = std::get_if(&value->value); + return text ? *text : std::string{}; +} + +std::int64_t remote_i64(const RemoteJson::Object &obj, const std::string &key) { + const auto *value = remote_find(obj, key); + if (!value) { + return 0; + } + const auto *number = std::get_if(&value->value); + return number ? *number : 0; +} + +std::optional parse_remote_record(std::string_view json_text, + const Graph::ActionNode &action, + const PathMapper &mapper) { + auto parsed = Void::Json::Strict::parse(json_text); + if (!parsed) { + return std::nullopt; + } + const auto *root = std::get_if(&parsed->value); + if (!root) { + return std::nullopt; + } + + State::ActionSuccessRecord record; + record.profile_identity = remote_str(*root, "profile_identity"); + record.target_name = remote_str(*root, "target_name"); + record.recorded_epoch = remote_i64(*root, "recorded_epoch"); + + const auto *outputs = remote_find(*root, "outputs"); + const auto *output_array = outputs ? std::get_if(&outputs->value) : nullptr; + if (!output_array || output_array->size() != action.declared_outputs.size()) { + return std::nullopt; + } + for (std::size_t i = 0; i < output_array->size(); ++i) { + const auto *obj = std::get_if(&(*output_array)[i].value); + if (!obj) { + return std::nullopt; + } + State::BlobRef ref; + ref.sha256 = remote_str(*obj, "sha256"); + ref.size = static_cast(remote_i64(*obj, "size")); + ref.mode = static_cast(remote_i64(*obj, "mode")); + if (ref.sha256.size() != 64) { + return std::nullopt; + } + record.outputs[action.declared_outputs[i].string()] = std::move(ref); + } + + if (const auto *discovered = remote_find(*root, "discovered_inputs")) { + if (const auto *array = std::get_if(&discovered->value)) { + for (const auto &item : *array) { + const auto *obj = std::get_if(&item.value); + if (!obj) { + continue; + } + const auto path = remote_str(*obj, "path"); + const auto digest = remote_str(*obj, "sha256"); + if (!path.empty() && !digest.empty()) { + record.discovered_inputs[mapper.denormalize(path)] = digest; + } + } + } + } + + if (const auto *guards = remote_find(*root, "lookup_guards")) { + if (const auto *array = std::get_if(&guards->value)) { + for (const auto &item : *array) { + const auto *obj = std::get_if(&item.value); + if (!obj) { + continue; + } + Snapshot::LookupGuard guard; + guard.lookup_name = remote_str(*obj, "lookup_name"); + guard.matched_root_index = static_cast(remote_i64(*obj, "matched_root_index")); + guard.matched_sha256 = remote_str(*obj, "matched_sha256"); + if (const auto *roots = remote_find(*obj, "search_roots")) { + if (const auto *root_array = std::get_if(&roots->value)) { + for (const auto &root_value : *root_array) { + if (const auto *text = std::get_if(&root_value.value)) { + guard.search_roots.push_back(mapper.denormalize(*text)); + } + } + } + } + record.lookup_guards.push_back(std::move(guard)); + } + } + } + return record; +} + std::set collect_ancestors(const Graph::BuildGraph &graph, const std::string &id) { std::set ancestors; std::queue q; @@ -309,6 +561,7 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, std::atomic started_exec_count{0}; bool abort_scheduling = false; RunDigestCache digest_cache; + const PathMapper path_mapper = make_path_mapper(graph); auto action_label = [&](const Graph::ActionNode &act) -> std::string { auto rel_name = [&](const std::filesystem::path &p) -> std::string { @@ -385,6 +638,40 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, } } + // 1b. Shared remote action cache lookup (Track D1) on local miss. + if (act.cacheable && !act.nondeterministic && options.use_cache && + state.has_remote_cache()) { + const std::string remote_key = + compute_remote_action_key(act, graph, digest_cache, path_mapper); + auto remote_json = state.fetch_remote_action(remote_key); + if (remote_json && remote_json->has_value()) { + auto remote_record = parse_remote_record(**remote_json, act, path_mapper); + bool usable = remote_record.has_value(); + if (usable) { + for (const auto &entry : remote_record->outputs) { + auto have = state.ensure_remote_blob(entry.second.sha256); + if (!have || !*have) { + usable = false; + break; + } + } + } + if (usable && + verify_discovered_inputs_unchanged(remote_record->discovered_inputs, + digest_cache) && + (verify_outputs_match_record(act, *remote_record, digest_cache) || + restore_outputs_from_cache(act, *remote_record, state, digest_cache))) { + remote_record->action_key = remote_key; + (void)state.record_action_success(*remote_record); + res.succeeded = true; + res.from_cache = true; + res.exit_code = 0; + res.elapsed = timer.elapsed_as(); + return res; + } + } + } + const std::size_t seq = started_exec_count.fetch_add(1, std::memory_order_relaxed) + 1; Void::Log::info("Build", "[{:>2}/{}] {}", seq, selected_indices.size(), label); emit_event(ExecutionEvent::Kind::ActionStarted, act, label, seq); @@ -529,6 +816,38 @@ execute_graph(const Graph::BuildGraph &graph, State::StateStore &state, committed.error().message()); return res; } + + // Best-effort publication to the shared remote cache (Track D1): blobs first, + // then the action record. Cache upload failures never fail the build. + if (state.has_remote_cache()) { + const std::string remote_key = + compute_remote_action_key(act, graph, digest_cache, path_mapper); + bool uploaded = true; + for (const auto &out : act.declared_outputs) { + const auto it = rec.outputs.find(out.string()); + if (it == rec.outputs.end()) { + uploaded = false; + break; + } + auto pushed = state.publish_remote_blob(it->second.sha256); + if (!pushed) { + Void::Log::warn("Remote", "Skipping remote cache upload for '{}': {}", + act.id, pushed.error().message()); + uploaded = false; + break; + } + } + if (uploaded) { + const auto json = serialize_remote_record(rec, act, path_mapper, remote_key); + if (!json.empty()) { + auto pushed = state.publish_remote_action(remote_key, json); + if (!pushed) { + Void::Log::warn("Remote", "Skipping remote action record for '{}': {}", + act.id, pushed.error().message()); + } + } + } + } } res.succeeded = true; diff --git a/src/Main.cpp b/src/Main.cpp index 1b1a0ea..b27d77a 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -502,6 +502,8 @@ struct BuildCmdOptions { std::optional editor_profile; std::optional compiler_arg; std::optional jobs_arg; + std::optional remote_cache_arg; + std::optional remote_cache_token_env; bool no_cache{false}; bool locked{false}; bool offline{false}; @@ -591,6 +593,21 @@ int execute_build_or_test(BuildCmdOptions opts, bool run_tests) { return 1; } + const std::string remote_cache_url = + opts.remote_cache_arg + ? *opts.remote_cache_arg + : std::string{Void::Configuration::get_env_or("VBS_REMOTE_CACHE", "")}; + if (!remote_cache_url.empty()) { + State::RemoteCacheConfig remote_cfg; + remote_cfg.url = remote_cache_url; + const std::string token_env = opts.remote_cache_token_env + ? *opts.remote_cache_token_env + : std::string{"VBS_REMOTE_CACHE_TOKEN"}; + remote_cfg.bearer_token = Void::Configuration::get_env_or(token_env, ""); + state->configure_remote_cache(std::move(remote_cfg)); + Void::Log::info("Cache", "Using shared remote action cache at {}", remote_cache_url); + } + const auto lock_path = project_root / "vbs.lock"; auto pinned_lock = Package::load_pinned_lock(lock_path); if (!pinned_lock) { @@ -1980,6 +1997,11 @@ int main(int argc, char **argv) { .option_many("--build-source", "", "Additional build description source", build_opts.extra_build_sources) .option("--jobs", "-j", "Maximum parallel compilation/link jobs", build_opts.jobs_arg) + .option("--remote-cache", "", "Shared HTTP action cache URL (or VBS_REMOTE_CACHE)", + build_opts.remote_cache_arg) + .option("--remote-cache-token-env", "", + "Environment variable holding the remote cache bearer token", + build_opts.remote_cache_token_env) .flag("--locked", "", "Require existing up-to-date vbs.lock", build_opts.locked) .flag("--offline", "", "Disallow network fetches", build_opts.offline) .flag("--no-cache", "", "Bypass action cache reads", build_opts.no_cache) diff --git a/src/Provider/Translator.cpp b/src/Provider/Translator.cpp index 882c0f2..b1cb1d1 100644 --- a/src/Provider/Translator.cpp +++ b/src/Provider/Translator.cpp @@ -123,8 +123,11 @@ std::vector split_shell_tokens(std::string_view text) { } bool is_safe_system_link_flag(std::string_view tok) { + // GCC 16 ships an as-needed linker script for libgcc_s, which CMake exposes as + // `-lgcc_s_asneeded` in codemodel link fragments; it is a real system library. return tok == "-pthread" || tok == "-lpthread" || tok == "-ldl" || tok == "-lm" || - tok == "-lrt" || tok.starts_with("-Wl,"); + tok == "-lrt" || tok == "-lgcc" || tok == "-lgcc_s" || tok == "-lgcc_s_asneeded" || + tok.starts_with("-Wl,"); } std::string trim_copy(std::string_view sv) { diff --git a/src/Snapshot/Snapshot.cpp b/src/Snapshot/Snapshot.cpp index 9c472f1..7f9bc38 100644 --- a/src/Snapshot/Snapshot.cpp +++ b/src/Snapshot/Snapshot.cpp @@ -1,18 +1,22 @@ #include +#include #include #include #include #include #include +#include #include #include #include #include #include +#include #include #include +#include #include namespace Void::Build::Snapshot { @@ -32,6 +36,29 @@ bool is_excluded_name(std::string_view name, const std::vector &exc return std::ranges::contains(excluded, name); } +// Bounded-parallel index loop used for content hashing (Track D2). Small inputs stay +// sequential to avoid thread-pool startup overhead. +template void parallel_for_indices(std::size_t count, Fn fn) { + constexpr std::size_t kParallelThreshold = 32; + if (count < kParallelThreshold) { + for (std::size_t i = 0; i < count; ++i) { + fn(i); + } + return; + } + const std::size_t workers = + std::min(count, std::max(1u, std::thread::hardware_concurrency())); + Void::Concurrency::ThreadPool pool{workers}; + std::vector> futures; + futures.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + futures.push_back(pool.submit([&fn, i] { fn(i); })); + } + for (auto &future : futures) { + future.get(); + } +} + bool path_has_excluded_component(const std::filesystem::path &rel_path, const std::vector &excluded) { for (const auto &part : rel_path) { @@ -393,15 +420,24 @@ Void::Result::Result capture_snapshot( } // Revalidation pass before sealing: detect concurrent mutations during capture. - bool mutated = false; - for (const auto &[logical, src_path] : source_files_to_verify) { + // Content hashing runs on a bounded thread pool for large trees (Track D2). + std::vector> files_to_rehash; + files_to_rehash.reserve(source_files_to_verify.size()); + for (const auto &entry : source_files_to_verify) { + files_to_rehash.push_back(entry); + } + std::atomic mutated{false}; + parallel_for_indices(files_to_rehash.size(), [&](std::size_t i) { + if (mutated.load(std::memory_order_relaxed)) { + return; + } + const auto &[logical, src_path] = files_to_rehash[i]; auto rehash = Util::sha256_file_hex(src_path); if (!rehash || *rehash != snap.entries.at(logical).sha256) { - mutated = true; - break; + mutated.store(true, std::memory_order_relaxed); } - } - if (!mutated) { + }); + if (!mutated.load()) { for (const auto &[logical_dir, dir_path] : dirs_to_verify) { auto meta = Platform::stat_lstat(dir_path); if (!meta) { @@ -422,7 +458,7 @@ Void::Result::Result capture_snapshot( } } } - if (mutated) { + if (mutated.load()) { continue; } diff --git a/src/State/RemoteCache.cpp b/src/State/RemoteCache.cpp new file mode 100644 index 0000000..df95efc --- /dev/null +++ b/src/State/RemoteCache.cpp @@ -0,0 +1,355 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Build::State { +namespace { + +Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg) { + return Void::System::make_system_error(code, std::move(msg)); +} + +bool is_valid_sha256_hex(std::string_view hex) { + if (hex.size() != 64) { + return false; + } + return std::ranges::all_of( + hex, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }); +} + +struct ParsedUrl { + std::string scheme; + std::string host; + std::uint16_t port{80}; + std::string base_path; +}; + +Void::Result::Result parse_remote_url(std::string_view url) { + url = Void::Str::trim_ascii(url); + const auto sep = url.find("://"); + if (sep == std::string_view::npos) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache URL must include http:// or https://")}; + } + ParsedUrl out; + out.scheme = Void::Str::to_lower_ascii(url.substr(0, sep)); + if (out.scheme != "http" && out.scheme != "https") { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "unsupported remote cache URL scheme")}; + } + const auto rest = url.substr(sep + 3); + const auto slash = rest.find('/'); + const auto authority = slash == std::string_view::npos ? rest : rest.substr(0, slash); + out.base_path = + slash == std::string_view::npos ? std::string{} : std::string{rest.substr(slash)}; + while (!out.base_path.empty() && out.base_path.back() == '/') { + out.base_path.pop_back(); + } + const auto colon = authority.rfind(':'); + if (colon != std::string_view::npos) { + out.host = std::string{authority.substr(0, colon)}; + int p = 0; + if (!Void::Str::to_int(authority.substr(colon + 1), p) || p <= 0 || p > 65535) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "invalid port in remote cache URL")}; + } + out.port = static_cast(p); + } else { + out.host = std::string{authority}; + out.port = out.scheme == "https" ? 443 : 80; + } + if (out.host.empty()) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "empty host in remote cache URL")}; + } + return out; +} + +struct HttpReply { + std::uint16_t status{0}; + std::string body; +}; + +bool send_all(int fd, std::string_view data) { + std::size_t off = 0; + while (off < data.size()) { + const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + off += static_cast(n); + } + return true; +} + +Void::Result::Result +http_exchange(const ParsedUrl &parsed, std::string_view method, std::string_view path, + const std::map> &headers, + std::string_view body) { + const std::string full_path = parsed.base_path + std::string{path}; + + if (parsed.scheme == "http") { + struct addrinfo hints{}; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + struct addrinfo *res = nullptr; + const std::string port_s = std::to_string(parsed.port); + if (::getaddrinfo(parsed.host.c_str(), port_s.c_str(), &hints, &res) != 0 || !res) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::io_error, + std::format("remote cache: failed resolving host '{}'", parsed.host))}; + } + auto free_ai = Void::Scope::on_exit([&] { ::freeaddrinfo(res); }); + + const int fd = ::socket(res->ai_family, res->ai_socktype | SOCK_CLOEXEC, res->ai_protocol); + if (fd < 0) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "remote cache: socket() failed")}; + } + Void::System::OwnedFd guard{fd}; + + struct timeval tv{60, 0}; + (void)::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + (void)::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + + if (::connect(fd, res->ai_addr, res->ai_addrlen) != 0) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("remote cache: connect to {}:{} failed", parsed.host, parsed.port))}; + } + + std::string req = std::format("{} {} HTTP/1.1\r\nHost: {}:{}\r\nConnection: close\r\n" + "Content-Length: {}\r\n", + method, full_path, parsed.host, parsed.port, body.size()); + for (const auto &[k, v] : headers) { + req += k + ": " + v + "\r\n"; + } + req += "\r\n"; + req += body; + if (!send_all(fd, req)) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::io_error, "remote cache: send() failed")}; + } + + std::string raw; + std::array buf{}; + for (;;) { + const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0); + if (n > 0) { + raw.append(buf.data(), static_cast(n)); + } else if (n == 0) { + break; + } else if (errno != EINTR) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "remote cache: recv() failed")}; + } + } + + const auto hdr_end = raw.find("\r\n\r\n"); + if (hdr_end == std::string::npos) { + return std::unexpected{make_error(Void::System::SystemErrorCode::io_error, + "remote cache: malformed HTTP response")}; + } + HttpReply reply; + const auto first_crlf = raw.find("\r\n"); + const std::string_view status_line{ + raw.data(), first_crlf == std::string::npos ? raw.size() : first_crlf}; + const auto sp1 = status_line.find(' '); + if (sp1 != std::string_view::npos) { + int code = 0; + if (Void::Str::to_int(status_line.substr(sp1 + 1, 3), code)) { + reply.status = static_cast(code); + } + } + reply.body = raw.substr(hdr_end + 4); + return reply; + } + + // HTTPS via curl preserves TLS certificate verification (never disables TLS). + auto curl = Platform::resolve_executable("curl"); + if (!curl) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::not_found, + "HTTPS remote cache requires curl (Void::Net not linked)")}; + } + const std::string full_url = + std::format("https://{}:{}{}", parsed.host, parsed.port, full_path); + Platform::ProcessRequest req; + req.executable = *curl; + req.arguments = {"--silent", "--show-error", "--proto", "=https", + "-X", std::string{method}, "-w", "\n%{http_code}"}; + for (const auto &[k, v] : headers) { + req.arguments.push_back("-H"); + req.arguments.push_back(k + ": " + v); + } + if (!body.empty()) { + req.arguments.push_back("--data-binary"); + req.arguments.push_back("@-"); + req.stdin_data = std::string{body}; + } + req.arguments.push_back(full_url); + req.timeout = std::chrono::seconds{120}; + auto proc = Platform::run_supervised(req); + if (!proc || !proc->succeeded()) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::io_error, + std::format("remote cache HTTPS request failed: {}", + proc ? proc->stderr_data : proc.error().message()))}; + } + HttpReply reply; + const auto nl = proc->stdout_data.rfind('\n'); + if (nl != std::string::npos) { + int code = 0; + if (Void::Str::to_int(Void::Str::trim_ascii(proc->stdout_data.substr(nl + 1)), code)) { + reply.status = static_cast(code); + } + reply.body = proc->stdout_data.substr(0, nl); + } + return reply; +} + +std::map> auth_headers(const RemoteCacheConfig &config) { + std::map> headers; + if (!config.bearer_token.empty()) { + headers["Authorization"] = "Bearer " + config.bearer_token; + } + return headers; +} + +Void::Result::Result require_url(const RemoteCacheConfig &config) { + if (config.url.empty()) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache is not configured")}; + } + return parse_remote_url(config.url); +} + +} // namespace + +RemoteCasClient::RemoteCasClient(RemoteCacheConfig config) : config_{std::move(config)} {} + +Void::Result::Result +RemoteCasClient::put_blob(std::string_view sha256, std::string_view bytes) const { + if (!is_valid_sha256_hex(sha256)) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache: invalid blob SHA-256")}; + } + auto parsed = require_url(config_); + if (!parsed) { + return std::unexpected{parsed.error()}; + } + auto headers = auth_headers(config_); + headers["Content-Type"] = "application/octet-stream"; + const std::string path = "/api/v1/cas/blobs/" + std::string{sha256}; + auto reply = http_exchange(*parsed, "PUT", path, headers, bytes); + if (!reply) { + return std::unexpected{reply.error()}; + } + if (reply->status != 200 && reply->status != 201) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("remote cache: blob upload failed with HTTP {}", reply->status))}; + } + return {}; +} + +Void::Result::Result, Void::Result::Error> +RemoteCasClient::get_blob(std::string_view sha256) const { + if (!is_valid_sha256_hex(sha256)) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache: invalid blob SHA-256")}; + } + auto parsed = require_url(config_); + if (!parsed) { + return std::unexpected{parsed.error()}; + } + const std::string path = "/api/v1/cas/blobs/" + std::string{sha256}; + auto reply = http_exchange(*parsed, "GET", path, auth_headers(config_), {}); + if (!reply) { + return std::unexpected{reply.error()}; + } + if (reply->status == 404) { + return std::optional{}; + } + if (reply->status != 200) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("remote cache: blob download failed with HTTP {}", reply->status))}; + } + if (Util::sha256_hex(reply->body) != sha256) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache: downloaded blob failed SHA-256 verification (discarded)")}; + } + return std::optional{std::move(reply->body)}; +} + +Void::Result::Result +RemoteCasClient::put_action(std::string_view action_key, std::string_view json) const { + if (!is_valid_sha256_hex(action_key)) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache: invalid action key")}; + } + auto parsed = require_url(config_); + if (!parsed) { + return std::unexpected{parsed.error()}; + } + auto headers = auth_headers(config_); + headers["Content-Type"] = "application/json"; + const std::string path = "/api/v1/cas/actions/" + std::string{action_key}; + auto reply = http_exchange(*parsed, "PUT", path, headers, json); + if (!reply) { + return std::unexpected{reply.error()}; + } + if (reply->status != 200 && reply->status != 201) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("remote cache: action upload failed with HTTP {}", reply->status))}; + } + return {}; +} + +Void::Result::Result, Void::Result::Error> +RemoteCasClient::get_action(std::string_view action_key) const { + if (!is_valid_sha256_hex(action_key)) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "remote cache: invalid action key")}; + } + auto parsed = require_url(config_); + if (!parsed) { + return std::unexpected{parsed.error()}; + } + const std::string path = "/api/v1/cas/actions/" + std::string{action_key}; + auto reply = http_exchange(*parsed, "GET", path, auth_headers(config_), {}); + if (!reply) { + return std::unexpected{reply.error()}; + } + if (reply->status == 404) { + return std::optional{}; + } + if (reply->status != 200) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("remote cache: action download failed with HTTP {}", reply->status))}; + } + return std::optional{std::move(reply->body)}; +} + +} // namespace Void::Build::State diff --git a/src/State/StateStore.cpp b/src/State/StateStore.cpp index 8f3efef..656527b 100644 --- a/src/State/StateStore.cpp +++ b/src/State/StateStore.cpp @@ -512,6 +512,102 @@ StateStore::materialize_blob(const BlobRef &ref, const std::filesystem::path &de return {}; } +void StateStore::configure_remote_cache(std::optional config) { + if (config && !config->url.empty()) { + remote_.emplace(std::move(*config)); + } else { + remote_.reset(); + } +} + +Void::Result::Result, Void::Result::Error> +StateStore::fetch_remote_action(std::string_view action_key) const { + if (!remote_) { + return std::optional{}; + } + return remote_->get_action(action_key); +} + +Void::Result::Result +StateStore::publish_remote_action(std::string_view action_key, std::string_view json) const { + if (!remote_) { + return {}; + } + return remote_->put_action(action_key, json); +} + +Void::Result::Result +StateStore::publish_remote_blob(std::string_view sha256) const { + if (!remote_) { + return {}; + } + if (!is_valid_sha256_hex(sha256)) { + return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, + "StateStore: invalid CAS blob digest")}; + } + auto bytes = Void::FileSystem::read_file(cas_blob_path(sha256)); + if (!bytes) { + return std::unexpected{bytes.error()}; + } + if (Util::sha256_hex(*bytes) != sha256) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::invalid_argument, + std::format("StateStore: refusing to upload corrupted CAS blob '{}'", sha256))}; + } + return remote_->put_blob(sha256, *bytes); +} + +Void::Result::Result +StateStore::ensure_remote_blob(std::string_view sha256) { + if (!is_valid_sha256_hex(sha256)) { + return false; + } + auto local = verify_blob(sha256); + if (!local) { + return std::unexpected{local.error()}; + } + if (*local) { + return true; + } + if (!remote_) { + return false; + } + auto fetched = remote_->get_blob(sha256); + if (!fetched) { + return std::unexpected{fetched.error()}; + } + if (!fetched->has_value()) { + return false; + } + const std::string &bytes = **fetched; + if (Util::sha256_hex(bytes) != sha256) { + return false; + } + + const auto final_path = cas_blob_path(sha256); + std::error_code ec; + std::filesystem::create_directories(final_path.parent_path(), ec); + const auto stage_path = + staging_dir_ / std::format("remote_{}_{}.stage", sha256, + g_lease_seq.fetch_add(1, std::memory_order_relaxed)); + auto wrote = Platform::atomic_write_file(stage_path, bytes, true, 0644); + if (!wrote) { + return std::unexpected{wrote.error()}; + } + (void)::chmod(stage_path.c_str(), 0444); + std::filesystem::rename(stage_path, final_path, ec); + if (ec) { + std::filesystem::remove(stage_path, ec); + if (!std::filesystem::exists(final_path)) { + return std::unexpected{make_error( + Void::System::SystemErrorCode::io_error, + std::format("StateStore: failed publishing remote CAS blob '{}'", sha256))}; + } + } + (void)Platform::fsync_directory(final_path.parent_path()); + return true; +} + Void::Result::Result, Void::Result::Error> StateStore::lookup_action(std::string_view action_key) const { std::optional found; diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp index c8462f0..530e66c 100644 --- a/tests/RegistryTests.cpp +++ b/tests/RegistryTests.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -215,6 +216,147 @@ VOID_TEST(RegistryTests, registry_rbac_immutability_csrf_xss_web_and_backup_rest } } +// Track D1: shared HTTP content-addressed action cache blob/record round-trip across stores. +VOID_TEST(RegistryTests, shared_remote_action_cache_blob_and_record_roundtrip) { + Void::FileSystem::TempDir tmp{"vbs_remote_cas_"}; + RegistryConfig cfg; + cfg.data_dir = tmp / "reg_data"; + cfg.bind_address = "127.0.0.1"; + cfg.port = 0; + cfg.bootstrap_admin_user = "admin"; + cfg.bootstrap_admin_password = "admin_pw"; + + auto svc = RegistryService::open(cfg); + Void::Testing::expect(svc.has_value()); + if (!svc) { + return; + } + Void::Testing::expect((*svc)->create_user("ci_cache", "ci_pass", Role::Publisher).has_value()); + auto tok = (*svc)->create_token("ci_cache", "cas", {"read", "publish"}); + Void::Testing::expect(tok.has_value()); + if (!tok) { + return; + } + Void::Testing::expect((*svc)->start_http().has_value()); + const auto port = (*svc)->bound_port(); + + State::RemoteCacheConfig remote; + remote.url = "http://127.0.0.1:" + std::to_string(port); + remote.bearer_token = *tok; + + Void::FileSystem::TempDir store_tmp{"vbs_remote_store_"}; + auto store = State::StateStore::open(store_tmp / ".vbs"); + Void::Testing::expect(store.has_value()); + if (!store) { + return; + } + store->configure_remote_cache(remote); + + const auto artifact = tmp / "remote_obj.o"; + (void)Platform::atomic_write_file(artifact, "REMOTE_CACHE_OBJECT_BYTES", false); + auto blob = store->store_blob_from_file(artifact); + Void::Testing::expect(blob.has_value()); + if (!blob) { + return; + } + Void::Testing::expect(store->publish_remote_blob(blob->sha256).has_value()); + + // A fresh, empty store downloads and SHA-256 verifies the blob from the shared cache. + Void::FileSystem::TempDir store2_tmp{"vbs_remote_store2_"}; + auto store2 = State::StateStore::open(store2_tmp / ".vbs"); + Void::Testing::expect(store2.has_value()); + if (!store2) { + return; + } + store2->configure_remote_cache(remote); + Void::Testing::expect(!store2->verify_blob(blob->sha256).value_or(true)); + auto ensured = store2->ensure_remote_blob(blob->sha256); + Void::Testing::expect(ensured.has_value() && *ensured); + Void::Testing::expect(store2->verify_blob(blob->sha256).value_or(false)); + + // Action record round-trip by portable key. + const std::string key = Util::sha256_hex("portable-action-key"); + const std::string record = "{\"schema_version\":1,\"action_key\":\"" + key + "\"}"; + Void::Testing::expect(store->publish_remote_action(key, record).has_value()); + auto fetched = store2->fetch_remote_action(key); + Void::Testing::expect(fetched.has_value() && fetched->has_value() && **fetched == record); + + // Unauthenticated CAS reads are rejected. + auto anon = send_loopback_http(port, "GET", "/api/v1/cas/blobs/" + blob->sha256); + Void::Testing::expect(anon.has_value() && anon->status == 401); + (*svc)->stop_http(); +} + +// Track D1 acceptance: a cold build populates the shared CAS, then a second clean build +// directory is a 100% verified cache hit and its binary runs. +VOID_TEST(RegistryTests, shared_remote_cache_cold_populates_then_clean_build_all_hits) { + 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_remote_accept_"}; + RegistryConfig cfg; + cfg.data_dir = tmp / "reg_data"; + cfg.bind_address = "127.0.0.1"; + cfg.port = 0; + cfg.bootstrap_admin_user = "admin"; + cfg.bootstrap_admin_password = "admin_pw"; + + auto svc = RegistryService::open(cfg); + Void::Testing::expect(svc.has_value()); + if (!svc) { + return; + } + Void::Testing::expect((*svc)->create_user("ci_cache", "ci_pass", Role::Publisher).has_value()); + auto tok = (*svc)->create_token("ci_cache", "accept", {"read", "publish"}); + Void::Testing::expect(tok.has_value()); + if (!tok) { + return; + } + Void::Testing::expect((*svc)->start_http().has_value()); + const std::string reg_url = "http://127.0.0.1:" + std::to_string((*svc)->bound_port()); + + const auto proj = tmp / "proj"; + (void)Platform::atomic_write_file(proj / "build.cpp", R"cpp(#include +void build(Void::Build::Project &p) { + p.executable("cache_app").sources({"src/main.cpp"}); +} +)cpp", + false); + (void)Platform::atomic_write_file(proj / "src" / "main.cpp", "int main() { return 0; }\n", + false); + + auto run_build = [&](const std::filesystem::path &build_dir) { + Platform::ProcessRequest req; + req.executable = vbs_bin; + req.arguments = {"build", "--project", proj.string(), + "--build-dir", build_dir.string(), "--remote-cache", + reg_url, "--jobs", "4"}; + req.environment.set_vars["VBS_REMOTE_CACHE_TOKEN"] = *tok; + return Platform::run_supervised(req); + }; + + auto first = run_build(tmp / "build_a"); + Void::Testing::expect(first.has_value() && first->succeeded()); + if (first) { + Void::Testing::expect(first->stdout_data.find("built (0 executed") == std::string::npos); + } + + auto second = run_build(tmp / "build_b"); + Void::Testing::expect(second.has_value() && second->succeeded()); + if (second) { + Void::Testing::expect(second->stdout_data.find("built (0 executed") != std::string::npos); + } + + Platform::ProcessRequest run_req; + run_req.executable = tmp / "build_b" / "profiles" / "debug" / "out" / "bin" / "cache_app"; + auto run_res = Platform::run_supervised(run_req); + Void::Testing::expect(run_res.has_value() && run_res->succeeded()); + (*svc)->stop_http(); +} + // End-to-end live client <-> server test: `vbs publish` -> `vbs deps resolve` -> `vbs build // --locked`! VOID_TEST(RegistryTests, cli_publish_deps_resolve_and_locked_build_against_live_registry) {