docs: add VoidBuildSystem handbook

This commit is contained in:
faumaray committed 2026-12-06 12:58:59 +03:00
1 parent 1f9a5d5804
commit 00e14bae98
19 files changed
+3240

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
---
title: Architecture and Control Flow
description: The layers, libraries and invariants behind VoidBuildSystem's configuration, execution, packaging and registry paths
section: Architecture
badge: design
order: 1
tags: [architecture, layers, components, invariants, control-flow, source-map]
updated: 2026-12-06
---
# Architecture and Control Flow
VoidBuildSystem is one binary (`vbs`) plus two support binaries (`vbs-registry`, `vbs_describe`) and a static SDK (`libVoidBuildSdk.a`). It is built on VoidLibrary for configuration, text, Unicode, concurrency, crypto, archives, logging, filesystem and process primitives. The project has two build front ends for its own source: a CMake bootstrap and a zero-CMake `build.cpp` that builds the same targets.
## End-to-end flow
:::flow
CLI → host descriptor → profiles → dependency resolution → immutable snapshot → graph lowering → scheduler → CAS publication → editor/daemon projections
:::
1. **Select roots and profiles.** The CLI resolves absolute project and build roots, loads the lockfile, discovers profiles, and pins a target OS/architecture and compiler family.
2. **Compile the description.** `build.cpp`, optional `build.profiles.cpp`, `build-support/**/*.cpp` and explicit `--build-source` files are compiled into a cached host executable against the fixed SDK. Configuration helpers are found by filesystem membership, not Git or a package graph.
3. **Evaluate out of process.** For each resolved `ProfileContext`, the descriptor writes one versioned JSON `ProjectDescription` to a private result file. stdout/stderr cannot corrupt the protocol.
4. **Resolve dependencies.** Inline C++ and TOML declarations merge, registry constraints solve, sources materialize and providers return typed `ImportedTargetInterface` values. The lock context is validated or republished.
5. **Capture a snapshot.** Declared source/include/search roots are captured into an immutable snapshot with content hashes, resolved symlinks, absence/lookup guards and isolated materialized bytes.
6. **Lower the graph.** Targets are validated, usage requirements are resolved transitively, modules are scanned/collated, and every target becomes typed actions: compile, PCH, header unit, module scan, BMI, archive, link or custom.
7. **Execute.** The scheduler runs the selected action closure with bounded parallelism, process-group supervision, depfile discovery, CAS lookup/publication and cancellation.
8. **Project metadata.** The same graph drives `compile_commands.json`, CMake File API replies, editor presets, IDE query JSON and daemon responses.
## Component map
| Area | Primary code | Responsibility |
| --- | --- | --- |
| Declaration SDK | `include/Void/Build.hpp`, `sdk/Build.cpp`, `sdk/Json.cpp` | Targets, profiles, dependencies, workspaces, deterministic JSON |
| Configuration frontend | `src/Config/Frontend.cpp`, `Presets.cpp`, `CmakeImport.cpp`, `Scaffold.cpp`, `BuildTree.cpp` | Descriptor compilation, profile discovery/evaluation, presets, `vbs init`, `vbs migrate`, clean |
| Graph | `src/Graph/Graph.cpp` | Target validation, usage propagation, source expansion, action lowering, output layout |
| Toolchain | `src/Toolchain/Driver.cpp` | Compiler discovery, capability probes, C/C++/ASM commands, modules, PCH, LTO, sanitizers |
| Snapshot | `src/Snapshot/Snapshot.cpp` | Namespace capture, hashing, reflink/copy isolation, lookup guards |
| Execution | `src/Execution/Scheduler.cpp` | DAG scheduling, parallelism, cache lookup, depfiles, cancellation |
| State | `src/State/StateStore.cpp`, `RemoteCache.cpp` | Local CAS, action records, generations, leases, GC, remote CAS |
| Editor | `src/Editor/CompDb.cpp` | Compilation databases, selection tickets, editor presets, File API shim, plugin assets |
| Modules | `src/Modules/ModuleScanner.cpp` | P1689 scan, BMI collation, header units, unity exclusions |
| Packages | `src/Package/{Toml,Solver,Lockfile,Archive,Fetch,Resolver,RegistryClient}.cpp` | Manifest model, solver, lock CAS, verification, providers' inputs |
| Providers | `src/Provider/{Provider,Translator,PkgConfig}.cpp` | Native, CMake, Meson, Conan, pkg-config; bounded native translation |
| Install / provenance | `src/Install/Installer.cpp`, `src/Provenance/*` | Prefix staging, exports, eight archives, SBOM, Ed25519, trusted keys |
| Reports | `src/Report/{Cdash,Coverage}.cpp` | JUnit-adjacent CDash XML and gcov/lcov |
| Daemon | `src/Daemon/Daemon.cpp` | Warm state/watcher, Unix-socket request protocol |
| Registry | `registry/service/*`, `registry/cli/Main.cpp`, `registry/web/*` | HTTP API, RBAC, CAS, workers, admin UI |
| Native recipes | `recipes/VoidLibrary/*`, `recipes/SelfHost/*` | Built-in VoidLibrary closure and the Stage 0→1 self-host recipe |
| CLI | `src/Main.cpp` | Argument parsing, orchestration, output; a thin adapter over libraries |
| Platform | `src/Platform/Linux/*`, `src/Watch/Linux/*`, `include/Void/Build/Platform/*` | Atomic files, process supervision, inotify/DirectoryWatcher, host detection |
Public libraries:
| CMake target | Alias | Contents |
| --- | --- | --- |
| `VoidBuild_Sdk` | `Void::BuildSdk` | Declaration SDK and JSON serialization |
| `VoidBuild_Core` | `Void::BuildCore` | Configuration, graph, execution, packages, providers, install, daemon, reports |
| `VoidBuild_Registry` | `Void::BuildRegistry` | Registry service (POSIX only) |
| `VoidBuild_Options` | — | C++26, `-freflection`, warnings interface |
## Invariants
:::callout{type="contract" title="Non-negotiable design rules"}
1. **Descriptions are host programs, not engine callbacks.** The engine never links a project's `build.cpp` into the CLI process.
2. **Profiles are isolated.** Objects, BMIs, PCHs, response files and generated headers are never shared between incompatible contexts.
3. **Inputs are immutable.** Successful actions run against captured inputs, not a mutable working tree in place.
4. **Outputs publish before references.** A CAS blob exists and verifies before an action success record refers to it.
5. **Determinism is the default.** Reproducibility epochs, canonical snapshot metadata, `-frandom-seed`, `SOURCE_DATE_EPOCH`, `TZ=UTC` and `LC_ALL=C` are applied unless the action is explicitly nondeterministic.
6. **Errors are explicit.** Missing tools, unsupported constructs, unresolved imported targets, stale locks and output collisions fail; they are not guessed or silently skipped.
7. **One owner per interface.** The shared schema (`schema_version: 1`) and lock format are versioned contracts between components.
:::
## Two execution identities
The build has three distinct tool identities:
| Identity | Used for | Not used for |
| --- | --- | --- |
| Host compiler | Compiling `build.cpp` and helper sources | Project targets |
| Target compiler | Compiling project sources | Evaluating the description |
| Build-machine tools | CMake, Meson, Conan, Git, shader compilers | Being assumed present in a target profile |
`build_dependency(true)` marks a dependency as a host/build-machine tool. In 1.0.0 the resolver records one target context (`machine_role = "target"`); the flag is carried in the model and lock entry, but a distinct build-machine solve is not implemented yet.
## What the graph owns
`BuildGraph` is the single execution contract:
- `profile` and `toolchain` identities;
- `snapshot_id` and the materialized root;
- `targets` with expanded sources, primary outputs, runtime libraries, labels, resources, fixtures and exported BMIs;
- topologically ordered `actions` with argv, environment, cwd, response files, declared inputs/outputs, depfile, logical/physical paths, compile metadata, cacheability and an action key.
Everything downstream — scheduler, compilation database, daemon responses, install staging, SBOMs — consumes this graph rather than re-deriving commands.
## Boundaries and ownership
- The **SDK** declares, the **frontend** compiles/evaluates, the **graph** validates and lowers, the **scheduler** executes.
- The **provider** returns complete usage requirements or an explicit gap; it never invents a library interface from a filename.
- The **registry** stores immutable bytes and policy metadata; it never executes recipes or verifies signatures on the server.
- The **daemon** is a transport and warm-state owner; it calls the same resolver/scheduler as the CLI and adds no alternate build algorithm.
- The **editor projection** rewrites typed operands onto logical sources; it never string-replaces arbitrary flags or defines.
The next page follows configuration and graph lowering in detail. See [Configuration and graphs](/build-system/developer/configuration-and-graph).
@@ -0,0 +1,195 @@
---
title: Configuration and Graph Lowering
description: How build.cpp is discovered, compiled and evaluated, how profiles resolve, and how targets become validated actions
section: Configuration & Execution
badge: internals
order: 1
tags: [internals, frontend, descriptor, profiles, graph, actions, modules, unity, pch]
updated: 2026-12-06
---
# Configuration and Graph Lowering
The frontend turns ordinary C++ into one immutable JSON description per profile; the graph layer turns that description plus a toolchain and snapshot into one immutable action graph. Neither step executes project targets.
## Description discovery
`discover_config_sources()` is filesystem-only:
- requires `build.cpp` **or** `workspace.cpp` at the project root;
- adds both if present (a workspace root takes precedence for orchestration);
- adds optional `build.profiles.cpp`;
- recursively globs `build-support/**/*.cpp|.cc|.cxx`, sorted;
- adds explicit `--build-source` files, resolved against the project root;
- de-duplicates by normalized path;
- never consults Git.
Headers are not enumerated up front. The compile step uses `-MMD` depfiles, and the discovered headers are recorded beside the descriptor for cache validation.
## Descriptor compilation
The descriptor is a host executable built against the fixed SDK:
```text
<build>/.vbs/config/
├── Driver.cpp
├── descriptor_<seed16>
├── descriptor_<seed16>.headers.json
├── obj_<seed16>/
├── identity_cache.json
└── seed.lock
```
`seed_identity_hash` covers:
- the host compiler path and its SHA-256;
- the generated driver source;
- `<sdk>/Void/Build.hpp` and the SDK library (or SDK sources);
- every configuration source's path and SHA-256.
Large files are hashed once and memoized by size + mtime in `identity_cache.json`. A cache hit also revalidates every previously discovered header (content hash; stat fingerprint short-circuit). If `build.profiles.cpp` is absent, the generated driver supplies `default_profiles()`. If `build.cpp` or `workspace.cpp` is absent, the driver supplies a throwing stub so the corresponding mode fails clearly.
Each translation unit is compiled with roughly:
```text
g++ -std=c++26 -O1 -I <project> -I <sdk> -MMD -MF <dep> -c <source> -o <object>
```
and linked into the descriptor. The host compiler defaults to `g++`; `--compiler gcc|clang` selects the **target** compiler and does not change the host compiler.
## Evaluation protocol
The descriptor runs out of process in `profiles`, `describe` or `workspace` mode. It writes a versioned JSON result to a private per-request file under `<build>/.vbs/config/eval/`. The parent enforces:
- bounded reads (16 MiB for profiles/workspace, 64 MiB for a project description);
- protocol version, request id and context hash checks;
- UTF-8 validation;
- a default 30 s evaluation timeout.
stdout and stderr are logs, not protocol. A `build.cpp` that prints arbitrary text cannot corrupt the result.
## Profile resolution
`Profiles::resolve(name, compiler_override, os, architecture)` walks the parent chain:
- unknown names, unknown parents, self-inheritance and cycles throw;
- ancestor fields apply first, then child fields;
- scalar fields are last-writer-wins;
- compile options, link options and defines are appended;
- sanitizers are de-duplicated;
- the compiler override applies last.
`default_profiles()` contains only:
| Profile | Compile options |
| --- | --- |
| `debug` | `-O0 -g` |
| `release` | `-O3 -DNDEBUG` |
No `-std`, PIC, LTO or sanitizer flag is added by default. `CStandard::Default` and `CxxStandard::Default` mean **no standard flag** unless a target or profile sets one, except module translation units, which force C++20 when the profile is Default.
The build root defaults to `<project>/build`, but a relative `--build-dir` is resolved against the current working directory, not the project root. A typical CI invocation passes an absolute path.
When multiple profiles are requested, `--editor-profile` must name one of them; this is checked before descriptor work.
## From description to graph
The pipeline after evaluation is:
```text
merge C++/TOML dependencies → validate/publish lock → materialize → import providers
→ capture snapshot → lower targets to actions → execute selected closure
```
`lower_project_graph()` receives the description, toolchain capabilities, project/build roots, an optional snapshot and imported targets. It produces `BuildGraph` with topologically ordered actions and no filesystem mutation except module scanning.
### Target validation
- duplicate target names;
- unknown prerequisite or local link targets;
- target-level cycles, reported as a chain;
- incompatible sanitizer combinations;
- missing explicit sources, header units or shader sources;
- custom actions without a command or output;
- duplicate output paths and outputs overlapping editable source files outside the profile build tree;
- Windows reserved device names and case-insensitive output collisions.
`enabled(false)` excludes a target from default selection, but its actions are still lowered and can be pulled in as prerequisites. Unknown `--target` names are errors.
### Usage propagation
For each local link:
- compile usage from the dependency is applied when the link visibility is `Public` or `Private` (not `Interface`);
- it is re-exported when the link visibility is `Public` or `Interface` (not `Private`);
- link inputs are always added in declaration order, dependency first, then transitive libraries;
- private dependencies of static libraries, header-only libraries and object libraries still propagate their link closure to final consumers; private dependencies of executables and shared libraries do not.
Imported targets follow the same compile-usage rules, with a link closure supplied by the provider. A missing imported target is an error.
### Actions
`ActionKind` values are `Compile`, `PrecompiledHeader`, `HeaderUnit`, `ModuleScan`, `ModuleBmi`, `Archive`, `Link` and `Custom`. `ModuleScan` exists in the enum but scanning currently runs synchronously during graph lowering, not as a scheduled action.
Action IDs are deterministic:
```text
compile:<target>:<sha12(source path)> pch:<target>
headerunit:<target>:<sha12> bmi:<target>:<sha12>
archive:<target> link:<target>
custom:<target> shader:<target>:<src>:<stage>
```
Each action carries argv, environment, working directory, optional response file, declared inputs/outputs, depfile, logical/physical source/output paths, include dirs, defines, options, standard/LTO/sanitizer/PIC/PCH metadata, dependency action ids, nondeterminism and an action key.
### Output layout
```text
<build>/profiles/<profile>/
├── .profile.lock
├── gen/ # custom action outputs and $GEN
├── obj/<target>/<file>_<sha12>.o + .d
├── obj/<target>/pch/<header>.gch
├── bmi/<target>/... # .gcm/.pcm, module mappers
├── modscan/<target>/
├── unity/<target>/
├── rsp/
├── shaders/<target>/
└── out/
├── lib<name>.a
├── lib<name>.so # POSIX shared library
├── <name>.dll # Windows shared library, directly in out/
└── bin/<name>[.exe]
```
A relative custom-action output goes under `gen/`; an absolute output must stay inside the profile build tree. The scheduler deletes a pre-existing static archive before `ar`, so removed objects do not linger in archive membership.
### Modules, header units, unity and PCH
- The P1689 scanner runs during lowering. GCC uses `-fdeps-format=p1689r5`; Clang uses `clang-scan-deps` with probed system include directories.
- Module collation rejects duplicate providers, self-imports, missing providers and cycles.
- BMIs are stored per target and profile identity. GCC uses a module mapper; Clang emits `.pcm` through a separate BMI action and compiles the `.pcm` to an object.
- Header units are lowered explicitly. Their default standard is C++20 when the profile standard is Default.
- Unity batches default to 8 and exclude `.c`, assembly, module sources and any source with a per-file option.
- PCH lowering exists, but capability probing and end-to-end coverage are weak in 1.0.0; treat PCH as experimental and verify it for your toolchain.
### Determinism inputs
The graph applies a reproducibility epoch and canonical path prefixes:
- `SOURCE_DATE_EPOCH=<epoch>`, `TZ=UTC`, `LC_ALL=C` on compile/custom/shader actions;
- snapshot root → project root and profile build dir → `/vbs-build` prefix maps;
- GCC `-frandom-seed=<object filename>` when deterministic;
- deterministic archive mode (`ar rcsD`).
Prefix maps are capability-checked. A compiler that supports none of the required mapping flags fails compilation instead of silently emitting non-reproducible objects. Link actions get `TZ`/`LC_ALL`, but no canonical output mtime in 1.0.0.
## Current limits
- Action keys include the whole-project `snapshot_id`, so a source edit re-keys every action; only a true no-op is fully cached. Single-file incremental reuse is not implemented.
- Snapshot lookup guards and `is_snapshot_fresh()` exist but are not populated/used by the CLI build path.
- `ModuleScan` is not a DAG action; scans are serial during lowering.
- PCH is unprobed; MemorySanitizer and LeakSanitizer requests are not capability-checked.
- Daemon builds lower without a snapshot, so their action keys differ from CLI builds.
Next: [trace snapshots, scheduling and state](/build-system/developer/snapshots-and-execution).
@@ -0,0 +1,275 @@
---
title: Packages, Solvers and Providers
description: The normalized dependency model, lockfile schema, fetch/cache layout, provider contracts and bounded foreign translation
section: Packages & Providers
badge: internals
order: 1
tags: [internals, solver, lockfile, fetch, providers, cmake, meson, conan, pkg-config, bridge]
updated: 2026-12-06
---
# Packages, Solvers and Providers
Package management is split into four stages with explicit boundaries:
:::flow
normalize → solve → lock/materialize → provide typed targets
:::
The C++ and TOML front ends produce the same `DependencyRecord`, the solver works only on registry packages, materialization produces a `MaterializedSource`, and a provider turns that source into `ImportedTargetInterface` values consumed by graph lowering.
## Normalized model
`DependencyRecord` (`include/Void/Build.hpp`) is the shared representation:
```text
name, source_kind, location, revision, package, version, builder,
options (string|bool|int64), registry_authority, sha256, features,
build_dependency
```
`DependencySourceKind` is `Git`, `Path`, `Archive`, `Package`, `Conan` or `PkgConfig`. Validation is immediate:
- exactly one source;
- Git requires a 40-hex commit; archive requires a 64-hex SHA-256;
- `.cmake()`/`.meson()` cannot be combined with a registry package source in C++;
- a builder cannot be reassigned;
- duplicate aliases are rejected.
C++ and TOML declarations merge by alias. Identical records merge; different records fail and report both origins. `build_dependencies` entries force `build_dependency = true`; the flag is recorded, but 1.0.0 resolves a single target context (`machine_role = "target"`).
### TOML loader details
The loader is intentionally strict:
- top-level tables: `dependencies`, `build_dependencies`, plus an accepted-but-unused `registries` placeholder;
- fields: `git`, `rev`, `path`, `archive`, `sha256`, `package`, `version`, `conan`, `builder`, `options`, `registry`, `features`, `build_dependency`;
- options are typed: string, bool or signed integer; floats, arrays and tables are rejected;
- `builder` must be `cmake`, `meson`, `conan` or `native`;
- a registry package may only use an explicit `native` builder; if the builder is omitted, `vbs build` inspects the extracted source for `build.cpp`, `CMakeLists.txt` or `meson.build`;
- diagnostics carry exact `file:line:column` origins;
- unknown keys and duplicate keys are never ignored.
## Solver
Registry identities are `{registry_authority, package_name}`. There is no cross-registry fallback: the same name from two authorities is two packages.
The solver is deterministic chronological backtracking with:
- fewest-candidates-first selection;
- fail-fast propagation and a bounded step count (`50,000`);
- pinned-version preference when not upgrading;
- highest compatible SemVer otherwise;
- yanked versions skipped unless they are the pinned version (configurable);
- up to eight `no version of <pkg> satisfies <range> (from <origin>)` explanations on failure.
:::callout{type="info" title="Naming vs implementation"}
The codebase and tests describe the solver as “PubGrub-style”. The current implementation does not use PubGrub incompatibility clauses or clause learning; it is a deterministic backtracking solver with pinned-version preference. Treat “PubGrub-style” as design lineage, not an algorithmic guarantee.
:::
Features are carried in constraints and lock entries, but do not affect acquisition or target export in 1.0.0. They are metadata for a future feature-aware solve.
The resolver always solves with `machine_role = "target"`. The API and lock schema allow a build role; a distinct build-machine solve is not implemented yet.
## Lockfile format
`vbs.lock` is JSON with `schema_version: 1`:
```json
{
"schema_version": 1,
"revision_hash": "sha256 over the canonical contexts payload",
"contexts": {
"debug:gcc:Linux:x86_64:target": {
"context_key": "debug:gcc:Linux:x86_64:target",
"profile_name": "debug",
"compiler": "gcc",
"os": "Linux",
"architecture": "x86_64",
"machine_role": "target",
"declaration_fingerprint": "…",
"entries": [
{
"alias": "fmt",
"source_kind": "package",
"registry_authority": "https://packages.example.com",
"package_name": "fmt",
"version": "11.0.2",
"location": "",
"revision": "",
"sha256": "…",
"builder": "native",
"features": ["header-only"],
"build_dependency": false,
"signature": "…",
"public_key": "…"
}
]
}
}
}
```
- `revision_hash` is re-computed and validated on read; a hand-edited hash is rejected.
- URLs are written without embedded credentials; bearer tokens never enter the lock.
- Optional signature fields are omitted when absent, preserving byte compatibility with unsigned locks.
- One immutable lock revision is pinned at build start.
`declaration_fingerprint` covers the profile name, compiler, OS, architecture, role, and every non-build dependency's normalized fields with typed options. Build-dependency declarations are written to lock entries but are excluded from the fingerprint in 1.0.0, so changing only a build dependency does not by itself force a lock republish.
Lock publication is compare-and-swap:
- `--locked` refuses creation or modification;
- a changed context is re-solved and republished by a normal build;
- a competing update to the same context with a different fingerprint returns busy;
- other profiles' contexts are preserved;
- multi-profile builds merge contexts instead of replacing the file.
## Materialization and cache
All dependency data lives under `<build>/.vbs/cache`:
| Content | Path |
| --- | --- |
| Registry tarball | `packages/<sha256>.tar` |
| Registry extracted source | `packages/<sha256>/src/` |
| Git checkout | `git/<alias>_<rev>/` with `.vbs_verified_rev` |
| Archive extraction | `archives/<sha256>/` with `.vbs_verified` |
| Archive download staging | `downloads/<sha256>.tar` |
| Fetch locks | `locks/<sha256>.lock`, `locks/git_<rev>.lock` |
| Path snapshot | `path-snapshots/` |
| Binary variant cache | `binaries/<sha256>` |
Materialization properties:
- **Path** dependencies are canonicalized, snapshotted for content identity, and never modified; `compile_commands.json` is excluded from the snapshot.
- **Archives** are verified before extraction. Local and `file://` sources are copied; remote sources use `curl` with HTTPS/HTTP only and a 120 s timeout. A digest mismatch deletes the download.
- **Git** uses `git clone --no-checkout` + detached checkout, then verifies `HEAD` equals the pinned commit. `GIT_TERMINAL_PROMPT=0` prevents interactive hangs. The checkout is published by atomic directory rename.
- **Registry packages** download with SHA-256 verification, extract safely, and reuse a cached extraction only while the expected directory exists.
- **Safe extraction** rejects absolute paths, `..`, symlinks, hardlinks, special files and duplicate entries, with entry/size/total quotas. Extraction is staged and published only on full success.
- **Integrity is checked before use**, and a cached extraction marker is not a substitute for an explicit re-verification when the source digest changes (the digest is part of the path).
Environment overrides: `VBS_VOID_SOURCE_DIR` (VoidLibrary only, Git source), `VBS_REGISTRY_URL`, `VBS_REGISTRY_TOKEN`, `VBS_TRUSTED_PUBLIC_KEYS`.
## Provider contract
A provider receives the materialized source, profile, toolchain and options, and returns `ImportedTargetInterface`:
```text
include_dirs (path, is_system), defines, compile_options, link_options,
static_libraries, shared_libraries, runtime_files, generated_prerequisites,
module_bmis
```
The graph then applies the same visibility and ordering rules as local targets. Missing imported targets are hard errors; a provider cannot return a partial interface and have it guessed.
### Native
`builder == "native"` requires a `build.cpp` or a recognized VoidLibrary tree (which uses the built-in recipe). The provider:
- sets `VBS_DEP_NAME`, `VBS_DEP_OPTION_<KEY>` and the plain option name (for VoidLibrary's `VOID_ENABLED_MODULES`-style options);
- evaluates/builds the dependency's graph through VBS itself;
- exports compile usage, reverse-post-order static link closure, runtime shared libraries, module BMIs and `Void_<Module>` → `Void::<Module>` aliases;
- supports static/shared/object/custom targets, plus executables for build dependencies;
- rejects nested dependencies inside a native subproject in 1.0.0.
No CMake is invoked on this path.
### CMake
Full-build mode writes a File API `codemodel-v2` query, configures CMake (Ninja if available), builds with `cmake --build`, and imports compile groups. It preserves only a small set of system link fragments (`-pthread`, `-lpthread`, `-ldl`, `-lm`, `-lrt`) and reconstructs static link order from dependencies.
Provider outputs are cached at `<build>/.vbs/providers/<dep>/<identity16>/provider-export.json`. The identity includes builder, source content hash, profile, toolchain identity and options. Metadata-only mode never executes CMake; an unbuilt provider returns `stale_needs_build` instead of fabricated targets.
### Meson
`meson setup` only, then `meson compile -C`, then reads `meson-info/intro-targets.json`. Static/shared targets, `-I` flags and `<src>/include` are imported. Defines and richer introspection are not imported in 1.0.0.
### Conan
The adapter checks for `conan` in `PATH`, writes host/build profiles, and runs `conan install --format json`. The current adapter imports no package targets beyond explicit overrides. A standalone `.conan(...)` source dependency also fails at materialization (`requires package/registry resolution before source fetch`), so it is not yet usable as a `vbs build` dependency.
### pkg-config
`.pc` files are parsed directly (no executable):
- recursive `${var}` expansion, including `${pcfiledir}`;
- comma-separated module specs with `=`, `==`, `!=`, `<`, `<=`, `>`, `>=` and RPM-style comparison;
- `Requires`, `Cflags`, `Libs` merged across the chain;
- `PKG_CONFIG_PATH`, then `PKG_CONFIG_LIBDIR` (which suppresses fallbacks), then conventional prefixes;
- `-I`/`-isystem<dir>` → include dirs (currently marked system), `-D` → defines, other cflags → compile options, `-l/-L/-Wl,/-pthread/-ldl` → link options, `.a`/`.so` → library inputs;
- lock entry as `pkgconfig`, never fetched.
Current gaps: `Requires.private`/`Libs.private` are ignored, a two-token `-isystem <dir>` is not parsed, and all include dirs are marked system.
### CMake bridge
`cmake/bridge/VbsDeps.cmake` lets a CMake project ask VBS for dependencies:
```cmake
include(VbsDeps.cmake)
vbs_declare_dependency(fmt PACKAGE fmt VERSION "^11.0" REGISTRY "https://...")
vbs_make_available(fmt)
```
The bridge writes a request JSON and calls `vbs bridge`, which materializes the source and imports provider targets as `IMPORTED` CMake targets. In 1.0.0 it cannot resolve registry `package` sources (the same materialization gap as Conan) and ignores `FEATURES`/`LOCKED`; use Git/path/archive sources in bridge mode.
## Bounded native translation
`--native-foreign` attempts to translate a foreign CMake/Meson graph into native VBS actions instead of delegating the build.
- **Policy**: `FallbackToForeignBuild` is the default and the only policy the CLI selects. `RequireNative` is available to library callers and fails on unsupported constructs.
- **CMake**: configure-only, audit `codemodel-v2`, lower compile/link groups and custom commands into a `BuildGraph`, execute with VBS's scheduler and CAS.
- **Meson**: `meson setup` only, audit `intro-targets.json`, recover link edges from `build.ninja`, lower custom targets.
- **Unsupported**: console pools, out-of-tree working directories/outputs, non-hermetic utility rules, build-system regeneration, unbounded shell custom commands, non-C/C++ languages, PCH, `run` targets, and untranslated dependency edges. Each is a named diagnostic, never a silent drop.
- **Caching**: translated provider graphs are not yet written as `provider-export.json`, so metadata-only readers such as `vbs ide` cannot see them until that is fixed.
## Signing and trust
Package signing uses Ed25519 over:
```text
vbs-package-v1
<name>@<version>
sha256:<archive-digest>
```
The trust policy is:
| Situation | Decision |
| --- | --- |
| No trusted keys configured | `Unsigned` (legacy behavior) |
| Missing signature/public key | `Unsigned` |
| Signer key not trusted | `UntrustedKey` (no crypto invoked) |
| Trusted key, valid signature | `Verified` |
| Trusted key, invalid signature | `InvalidSignature` |
| Malformed hex or no crypto backend | explicit error |
Enforcement happens in `vbs build`/`vbs test` and the daemon before extraction. `vbs deps resolve|update` do not accept trusted keys yet, so run a build (or `vbs verify`) when enforcing signatures in automation. Keys come from `--trusted-public-key`, `--trusted-key-file`, `vbs.keys`, and `VBS_TRUSTED_PUBLIC_KEYS`.
Binary variants use `vbs-binary-v1\n<variant-id>\nsha256:<digest>\n`; installer archives use `vbs-installer-v1\n<digest>\n` and sign the archive digest, not the bytes.
## Install and SBOM internals
`install_project` stages privately, validates destinations, then publishes file-by-file and writes `.vbs-install-manifest.json`. It installs only targets with install rules plus declared files. Public headers require an explicit `install_directory`. CMake exports are relocatable and skip executables; native metadata lives under `share/vbs/<pkg>/package.json`.
Installer archives are generated from the installed file list, so the ownership manifest itself is **not** included in the archive. `--bundle-dependencies` bundles only local shared-library outputs in 1.0.0, not imported provider libraries.
SBOMs include lock entries with a concrete version (registry packages) and all lowered target primary outputs. Git/path/archive/pkgconfig entries without a version are omitted; the document is deterministic for identical inputs.
## Current limits
:::callout{type="warning" title="Known 1.0.0 gaps"}
- Conan is not usable as a standalone `vbs build` dependency yet.
- Features are recorded but do not affect acquisition.
- Only the target machine role is solved.
- Build-dependency declarations are excluded from the lock fingerprint.
- `vbs deps update --offline` with registry packages always fails.
- `vbs install` has no `--locked`, `--offline` or `--native-foreign`.
- Downloads are buffered in memory rather than streamed.
- Foreign translation results are not cached as provider exports.
- Binary variants are verified but not selected by `vbs build`.
- pkg-config private requirements and two-token `-isystem` are unsupported.
:::
Next: [inspect the registry internals](/build-system/developer/registry-internals) or [trace execution and snapshots](/build-system/developer/snapshots-and-execution).
@@ -0,0 +1,138 @@
---
title: Quality, Benchmarks and Known Limits
description: Test suites, contract checks, fuzzing, benchmarks, platform status and the gaps to plan around in 1.0.0
section: Quality & Status
badge: status
order: 1
tags: [quality, testing, fuzzing, benchmarks, platforms, gaps, limitations, status]
updated: 2026-12-06
---
# Quality, Benchmarks and Known Limits
This page is deliberately conservative: it separates what is exercised from what is implemented, and records the gaps that matter when adopting or extending VBS 1.0.0.
## Test layers
| Layer | Entry point | What it proves |
| --- | --- | --- |
| Declaration SDK | `vbs_sdk_tests` | Target/profile records, visibility, handle lifetime, UTF-8 JSON |
| Core engine | `vbs_core_tests` | SHA-256, process supervision, profiles, snapshots, state/CAS, end-to-end build |
| v1 integration | `vbs_v1_tests` | CompDB, providers, packages, install, modules, daemon, signing, IDE, workspaces |
| Registry | `vbs_registry_tests` | HTTP API, RBAC, CSRF, CAS, remote cache, workers, live CLI E2E |
| Self-host | `vbs_selfhost_tests` | Native self-host, `VOID_TEST` generation, bit-identical rebuilds |
| SDK registration | `vbs_sdk_registration` | Self-registering cases and named execution |
| CLI contracts | `vbs_cli_contract` | Help, subcommands, repeatable flags, error contracts |
| Description contracts | `vbs_description_contract` | Four profile/compiler contexts and describe errors |
The CMake bootstrap exposes these as eight CTest entries. The self-hosted description declares the same suite executables as `project.test(...)` targets, so `vbs test` runs them without CMake.
```sh
dev cpp-gcc -c ctest --test-dir build --output-on-failure
build/bin/vbs test --build-dir build/vbs-stage2 --profile release --jobs 8
```
The integration suites create temporary projects, compile real binaries, start real registry servers on loopback, run CLI processes, and assert outputs and exit codes. A passing test run is the acceptance signal; a design document is not.
## What the suite exercises
- Native C/C++ builds, static/shared/object/header-only targets, custom actions, assembly, shaders.
- Profiles, inheritance, cycles, sanitizer compatibility, LTO and unity lowering.
- Snapshots, mutation detection, symlinks, header shadowing, state recovery and GC.
- GCC 16 and Clang 23 modules, partitions, header units, cross-target BMIs.
- CMake/Meson providers, bounded native translation, custom commands, mixed C/C++ and C++20 modules.
- TOML parsing, solver oracle, lock CAS, archive safety, install/relocation, CMake bridge.
- Registry RBAC, immutability, CSRF, XSS-safe UI, ETag/304, ranges, binary variants, yank.
- Remote cache round trips, worker leases/queue/execution, parallel workers.
- Daemon lifecycle and all request families.
- Signing primitives, trusted-key policy, lockfile signature round trips.
- Workspace member builds, shared lock/CAS, `--changed-since` selection.
- IDE compdb projection, ticket races, editor presets, File API replies, plugin assets.
- JUnit, CDash, coverage, test labels/resources/fixtures.
## What is not covered or not proven
:::callout{type="warning" title="Treat these as unverified until you reproduce them"}
- **PCH**: lowering exists, but there is no capability probe and no end-to-end PCH test.
- **MemorySanitizer / LeakSanitizer**: flags exist, but only ASan/UBSan/TSan are probed; MSan/LSan requests can fail at the compiler.
- **Native Windows host**: partial `_WIN32` backends exist, but `host_supported()` reports Linux only, the daemon and registry are not built on Windows, and CI only cross-builds and runs under Wine.
- **Wine-hosted suite**: SDK/core only, marked non-blocking; `vbs_v1_tests` and `vbs_selfhost_tests` do not run under Wine.
- **Daemon metadata requests** for projects that link provider-imported targets: they lower without imports and can fail.
- **Conan as a `vbs build` source dependency**: the adapter exists, but standalone `.conan(...)` materialization is not wired.
- **Single-file incremental rebuilds**: action keys include the whole snapshot id; only a true no-op is fully cached.
- **Streaming downloads**: package and registry responses are buffered in memory in 1.0.0.
- **CMake bridge package deps**: registry package sources cannot be materialized through the bridge.
- **Remote execution sandboxing**: none; action specs run with worker privileges.
- **Registry backup completeness**: the C++ backup helper omits binary blobs and the action cache.
:::
## Fuzzing
Two harnesses exist:
1. **Deterministic mutation harness** (`CoreEngineTests.fuzz_mutated_inputs_never_crash_parsers`): fixed-seed xorshift mutations, truncation, overwrite runs and junk insertion over TOML, JSON, lockfile and tar seeds; seed sanity checks prevent a vacuous run.
2. **Clang/libFuzzer target** (`fuzz/fuzz_parsers.cpp`, `fuzz/run.sh`): JSON, SemVer range and strict SemVer entry points, with a seeded corpus and ASan/UBSan.
The fuzz target covers header-only parsers. TOML, lockfile and tar stay in the deterministic mutation harness because their implementations are not header-only. Run:
```sh
dev cpp -c fuzz/run.sh
```
A clean fuzz run is evidence for crash resistance, not a proof of correctness.
## Benchmarks
`vbs_benchmarks --files N` measures engine operations. `benchmarks/compare.sh` generates a project and times VBS against CMake/Ninja and Meson for cold and warm builds.
```sh
build/bin/vbs_benchmarks --files 15
benchmarks/compare.sh 20
```
Benchmark numbers are environment-specific and have moved with optimization waves; measure on your own hardware and toolchain. The documented performance target is warm-build latency (descriptor identity caching, parallel snapshot hashing, stat-validated state), not a cross-tool marketing claim. Large-repo scaling and per-file incremental reuse remain open.
## Platform status
| Host / target | Status |
| --- | --- |
| Linux x86_64 host | Supported and exercised |
| Linux aarch64 host | Architecture-aware probes exist; not exercised in CI |
| Windows x86_64/aarch64 target from Linux | Supported via MinGW-w64; tests require Wine |
| Native Windows host | Partial port; not a supported host in 1.0.0 |
| macOS host/target | Deferred; backends are not implemented |
| Registry service | POSIX only |
| Daemon | POSIX only |
Cross-target builds emit PE artifacts (`.exe`, `.dll`). Static archives keep the `lib<name>.a` convention. Wine tests resolve the literal `wine` executable; `wine64` is not tried.
## Security and trust boundaries
- `build.cpp` is compiled native code with user privileges. Snapshots and process isolation are not a sandbox.
- Remote cache records and worker action specs are trusted input. A worker executes arbitrary commands from the registry.
- Registry private packages are hidden from anonymous access but readable by any authenticated `read` principal.
- Registry sessions, workers, leases and queues are in-memory and lost on restart.
- Bearer tokens are runtime-only and never written to locks or action records.
- Package signatures are verified by consumers, not by the registry. Installer signatures cover a canonical digest message.
- The registry has no built-in TLS, rate limiting or login throttling; deploy it behind a trusted proxy.
## Documentation status
This handbook documents **VoidBuildSystem 1.0.0** at the `v1.0.0` tag. The repository's `docs/roadmap/` contains historical design plans and some statements that lag the implementation (for example, features listed as planned that are now implemented, or pin hashes from earlier waves). When the handbook and a roadmap page disagree, prefer the code and the current tests, then update the page.
## Adoption checklist
:::steps
@@step[Verify the toolchain]
Run `vbs doctor` on every host and target combination you depend on.
@@step[Pin and lock]
Commit `vbs.lock`; use `--locked` in CI; decide whether to require trusted keys.
@@step[Prove the round trip]
Build, test, install, unpack the archive, and run the installed product from a clean prefix.
@@step[Check the edges]
Exercise the specific feature you rely on: PCH, Conan, daemon metadata, Wine tests or registry backup.
@@step[Measure]
Run the benchmark on your project before making performance claims.
:::
If a limitation above blocks adoption, treat it as a tracked gap rather than a configuration mistake. The design intentionally fails explicitly instead of approximating behavior.
@@ -0,0 +1,200 @@
---
title: Registry Service Internals
description: HTTP routes, authentication, storage layout, package and binary endpoints, remote cache and worker protocol
section: Registry & Remote
badge: registry
order: 1
tags: [internals, registry, http, rbac, csrf, storage, cas, workers, leases]
updated: 2026-12-06
---
# Registry Service Internals
`RegistryService` is a POSIX-only HTTP/1.1 service built on a small socket loop (or `Void::Net::HttpServer` when linked). It serializes API mutations on one mutex, stores package blobs and action-cache blobs on disk, and keeps users, tokens, packages, releases and audit records in one JSON metadata file.
## Startup and storage
`RegistryService::open(RegistryConfig)` creates:
```text
<data-dir>/
├── metadata.v1.json # users, tokens, packages, releases, audit
├── registry.lock # per-save advisory lock
├── cas/blobs/<2>/<sha256> # package + binary blobs, 0444
└── action-cache/
├── blobs/<2>/<sha256> # remote-cache outputs
└── actions/<2>/<sha256>.json # action records
```
`metadata.v1.json` is rewritten synchronously on every mutation under `registry.lock`. Package blobs are published before the metadata commit that references them. Sessions, workers, leases and the action queue are **in-memory only** and disappear on restart.
Configuration defaults:
| Setting | Default |
| --- | --- |
| `max_upload_bytes` | 32 MiB |
| `max_storage_bytes` | 2 GiB (source-release digests only) |
| `bootstrap_admin_user` | `admin` |
| Audit cap | 2000 entries (oldest 500 trimmed) |
`--web-root` defaults to `<Bootstrap::source_dir>/registry/web`, which is a source-tree path. Packaged deployments must point it at the installed assets.
## Transport
- HTTP/1.1, one request per connection (`Connection: close`).
- Header limit 64 KiB; body limit `max_upload_bytes`; 10 s socket timeouts.
- `HEAD` is routed as `GET` with the body suppressed and `Content-Length` preserved.
- Every response sets `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and a restrictive CSP.
- Errors are `{"error":{"code":"…","message":"…"}}`.
- `OPTIONS` is answered from route shape before authentication with `204` + `Allow`; no CORS `Access-Control-*` headers are emitted.
- A single `Range: bytes=…` is supported (206 + `Content-Range`, 416 for unsatisfiable/multipart).
## Authentication and authorization
Roles are `reader`, `publisher`, `admin`. Principal resolution order:
1. `Authorization: Bearer …` (hash lookup, constant-time compare, revoked/expired/inactive checks);
2. the `vbs_session` cookie.
Bearer requests are exempt from CSRF. Cookie-authenticated mutations require `X-CSRF-Token` matching the session token; if `Origin` is present it must be loopback HTTP or HTTPS.
Sessions:
- 24-byte session id and 24-byte CSRF token;
- stored hashed, 24-hour expiry, in memory only;
- cookie is `HttpOnly; SameSite=Strict; Path=/`, not `Secure` (fine on loopback, must be terminated by TLS behind a proxy).
Tokens:
- plaintext is `vbs_tok_` + 48 hex, returned once; only SHA-256 is stored;
- scopes are free-form, but only `read`, `publish`, `admin` are consulted;
- API-created tokens have no expiry; revocation is a soft flag;
- a token can mint another token up to its user's role, not beyond the calling token's scope (scope intersection is not implemented).
Private packages:
- public listing excludes them;
- anonymous access is `401`; an authenticated principal with `read` can read them;
- this is team visibility, not a per-user ACL;
- first publisher becomes sole owner; admin bypasses ownership; removing the last owner is `409 last_owner`.
## Routes
### Public/auth
| Method + path | Auth | Purpose |
| --- | --- | --- |
| `GET /api/v1/health` | none | `{"status":"ok","schema_version":1}` |
| `POST /api/v1/auth/login` | none | Session cookie + `csrf_token`; `401` on bad credentials |
| `POST /api/v1/auth/logout` | principal (+CSRF for cookie) | Clear session |
| `GET /api/v1/auth/me` | principal | Username, role, CSRF token |
| `GET /api/v1/packages` | optional | Search `q` + `limit`/`offset` envelope |
| `GET /api/v1/packages/<name>` | optional | Detail, owners, releases |
| `PATCH /api/v1/packages/<name>` | publish + CSRF | Description/private metadata |
| `GET /api/v1/packages/<name>/owners` | optional | Owner list |
| `PUT/POST/DELETE .../owners/<user>` | publish + CSRF | Owner management |
Search `q` is a case-sensitive substring over name and description. `limit` defaults to 100 and is capped at 500; `offset` is capped at 1,000,000. The response is `{packages,total,limit,offset}`.
### Releases and binaries
| Method + path | Auth | Purpose |
| --- | --- | --- |
| `GET .../packages/<name>/<version>` | optional | Release detail with digest, size, yank, publisher, signature, binary summaries |
| `PUT .../packages/<name>/<version>` | publish + CSRF | Raw source tar upload |
| `GET .../<version>/download` | optional | Tar download with `X-Content-SHA256` |
| `PUT .../<version>/binaries/<variant>` | publish + CSRF | Upload a binary variant |
| `GET .../<version>/binaries` | optional | List variants |
| `GET .../<version>/binaries/<variant>` | optional | Variant detail + `download_url` |
| `GET .../binaries/<variant>/download` | optional | Variant bytes |
| `POST .../<version>/yank` | publish + CSRF | Yank/unyank a release |
| `POST .../binaries/<variant>/yank` | publish + CSRF | Yank/unyank a variant |
Publish headers:
- `X-Content-SHA256`: must match the body (`400 digest_mismatch`);
- `X-Package-Description`, `X-Package-Private`;
- `X-Package-Signature` / `X-Package-Public-Key` (both-or-none, 128/64 hex);
- binary variants use `X-Binary-Signature` / `X-Binary-Public-Key`.
Immutable release semantics:
- identical bytes for an existing version → `200 already_published`;
- different bytes → `409 immutable_conflict`;
- malformed archive (traversal, symlink, duplicate, quota) → `422 invalid_archive`;
- storage quota → `413 quota_exceeded`.
Signature metadata is stored and served but never verified by the server. Trust belongs to the consumer.
Release and binary detail/listing responses carry a strong `ETag` and `Cache-Control: no-cache` and honour `If-None-Match` (weak prefixes, lists, `*`) with a bodyless `304`. Download `ETag`s are the artifact digest. Downloads support single ranges and `HEAD`.
Yanking only flips a flag; download routes still serve yanked bytes. Clients hide yanked variants from selection.
### Tokens, users, audit
| Method + path | Auth | Purpose |
| --- | --- | --- |
| `GET /api/v1/tokens` | principal | Own tokens; admin sees all |
| `POST /api/v1/tokens` | principal + CSRF | Create token, plaintext returned once |
| `DELETE /api/v1/tokens/<id>` | principal + CSRF | Revoke |
| `GET/POST /api/v1/users` | admin (+CSRF) | Paginated users / upsert |
| `GET /api/v1/audit` | admin | Filters `actor`, `action` substring, `outcome`; paginated |
| `GET /api/v1/admin/storage` | admin | Used/quota/package count |
| `GET /api/v1/stats` | admin | Counts + ETag |
`POST /api/v1/users` is an upsert: it can overwrite a password and role. There is no deactivate/reactivate route in 1.0.0.
Audit entries record timestamp, actor, action, target, outcome and redacted detail. Logins, token operations, user changes, publish/update/yank, owner changes, binary operations, CAS writes, worker registration and queue/lease actions are audited. Most 401/403 denials are not.
## Remote cache endpoints
| Method + path | Auth | Purpose |
| --- | --- | --- |
| `GET/PUT /api/v1/cas/blobs/<sha256>` | any principal | Raw blob store; `PUT` verifies the digest |
| `GET/PUT /api/v1/cas/actions/<action-key>` | any principal | JSON action record |
`PUT` returns `200` when the object already exists and `201` when created. The client re-verifies downloaded blobs. The server does not enforce package ownership on CAS objects.
## Worker and lease endpoints
| Method + path | Auth | Purpose |
| --- | --- | --- |
| `POST /api/v1/workers` | any principal | Register, returns `wrk_…` |
| `POST /api/v1/workers/<id>/heartbeat` | owner/admin | Refresh liveness |
| `GET /api/v1/workers` | owner/admin | List |
| `POST /api/v1/queue` | publish/admin | Enqueue up to 64-hex action keys |
| `GET /api/v1/queue` | any principal | Pending + leased keys |
| `POST /api/v1/queue/lease` | any principal | FIFO lease, optional `worker_id`, `lease_seconds` 1–3600 |
| `POST /api/v1/actions/lease` | any principal | Lease a specific key, returns the record |
| `POST /api/v1/actions/<key>/renew` | lease token | Extend lease |
| `POST /api/v1/actions/<key>/result` | lease token | Store result, require all output blobs, erase lease, dequeue |
Leases are pruned lazily. Results must reference an existing action record and every declared output blob must already be in the action-cache CAS; the endpoint then writes the record atomically. There is no per-tenant queue scoping, no worker affinity and no scheduling policy.
## Web UI
The static UI supports package search/detail, source release upload, release download/yank, token management, storage, user creation and the audit log. It renders with `textContent` and sends CSRF on mutations.
It does **not** implement binary-variant browsing/publishing, owner management, metadata editing or upload progress in 1.0.0. There is no automated headless-browser coverage of the UI.
## Backup and restore
`RegistryService::backup_to(dir)` and `restore_from(dir)` exist in the C++ API but have no CLI or HTTP route. They copy metadata and source-release blobs only; binary blobs and the entire action cache are excluded. Restore is additive and does not verify blob digests.
For a complete backup, stop the writer and copy the entire data directory. That is the only path that preserves binary variants, action-cache blobs and metadata together.
## Security model and limits
- Loopback default; TLS is expected from a reverse proxy.
- No rate limiting, login throttling, automatic token expiry, user deactivation or per-user private-package ACL.
- Private package existence is distinguishable: missing is `404`, private is `401` anonymous.
- Path segments are not percent-decoded; clients URL-encode names and versions.
- Upload bodies are buffered in memory (32 MiB cap), not streamed.
- Metadata is one JSON file; there is no SQLite registry backend.
- Sessions/queue/leases are lost on restart.
- `OPTIONS` is not a real CORS preflight.
- Reason phrases for some non-200 statuses are emitted as `OK`.
These are operational constraints to plan around, not hidden behavior; the implementation fails explicitly rather than pretending a stronger guarantee.
Next: [reproduce a self-hosted release](/build-system/developer/self-hosting).
+150
View File
@@ -0,0 +1,150 @@
---
title: Self-Hosting, CI and Releases
description: Bootstrap stages, the zero-CMake build description, bit-identical rebuilds, the CI matrix and release packaging
section: Self-Hosting & Releases
badge: zero-CMake
order: 1
tags: [self-host, bootstrap, reproducible, ci, gitea, release, installers, voidlibrary]
updated: 2026-12-06
---
# Self-Hosting, CI and Releases
VoidBuildSystem does not need CMake to build itself. The CMake bootstrap produces the first `vbs`; that binary then builds VoidLibrary through `.native_builder(...)`, declares all VBS targets in root [`build.cpp`](https://git.faumaray.com/Void/Build-System/src/branch/main/build.cpp), runs the native test suites, and packages its own installers.
## Stage model
:::flow
CMake bootstrap → self-built vbs (stage 2) → rebuilt vbs (stage 3) → bit-identical comparison
:::
| Stage | Producer | Purpose |
| --- | --- | --- |
| Bootstrap | CMake + GCC 16 | Build the first `vbs`, `vbs-registry`, `vbs_describe`, benchmarks and tests |
| Stage 2 | Bootstrap `vbs` | Build VoidLibrary natively, then VBS, then run `VOID_TEST` suites with CMake trapped |
| Stage 3 | Stage 2 `vbs` | Rebuild in a separate build directory without cache and compare artifacts |
The current root description pins VoidLibrary `de1fdcda72ddd6ac069fba433b13f643327efa3f` and requests the modules VBS needs:
```cpp
library.git("https://git.faumaray.com/Void/VoidLibrary.git",
Void::Build::Commit{"de1fdcda72ddd6ac069fba433b13f643327efa3f"})
.native_builder({{"VOID_ENABLED_MODULES",
"Configuration;Text;Unicode;Async;Algorithms;Crypto;Archive;Testing;Log"},
{"VOID_ENABLE_TESTING", "0"},
{"BUILD_SHARED_LIBS", false}});
```
The description declares 13 targets:
- `VoidBuildSdk`, `VoidBuildCore`, `GenerateBootstrapConfig`;
- `vbs`, `VoidBuildRegistry`, `vbs-registry`;
- `vbs_self_smoke`, `vbs_benchmarks`;
- `vbs_sdk_tests`, `vbs_core_tests`, `vbs_v1_tests`, `vbs_registry_tests`, `vbs_selfhost_tests`.
Source membership is convention-based: `sdk/*.cpp`, `src/*/*.cpp`, `src/*/*/*.cpp`, `recipes/**/*.cpp` and `registry/service/*.cpp`. The entry points are excluded from the core library glob.
## Commands
```sh
# Bootstrap
dev cpp-gcc -c cmake -S . -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
dev cpp-gcc -c cmake --build build --parallel 4
dev cpp-gcc -c ctest --test-dir build --output-on-failure
# Stage 2: build and test the whole project without CMake
VBS_VOID_SOURCE_DIR=/path/to/VoidLibrary \
build/bin/vbs test --build-dir build/vbs-stage2 --profile release --jobs 8
# Stage 3: rebuild in a clean directory without cache
build/vbs-stage2/profiles/release/out/bin/vbs build \
--build-dir build/vbs-stage3 --profile release --target vbs --no-cache --jobs 8
# Reproducibility check
sha256sum build/vbs-stage2/profiles/release/out/bin/vbs \
build/vbs-stage3/profiles/release/out/bin/vbs
```
`VBS_VOID_SOURCE_DIR` is a development override for the **VoidLibrary** Git dependency only. It never modifies the external checkout and does not change the pin in the description.
### What makes the rebuild reproducible
- `BootstrapConfig.hpp` is generated per profile; `binary_dir` is empty, so the binary resolves its SDK/binary directory relative to itself.
- The snapshot materialized root maps to the project root and the profile build directory maps to `/vbs-build`.
- GCC compiles get `-frandom-seed=<object filename>`.
- Links set `TZ=UTC` and `LC_ALL=C`.
- Static archives use deterministic mode.
- Installer/source archives use canonical timestamps and sorted entries.
Bit-identical output is an observed property of the VBS-to-VBS stages, not a claim that every external tool is deterministic. Keep the same compiler, binutils and build flags when comparing.
## VoidLibrary recipe and migration
The native provider has two paths:
- **Generic `build.cpp` subproject**: evaluates the dependency's own description and imports its exported targets.
- **Built-in VoidLibrary recipe** (`recipes/VoidLibrary/VoidLibraryRecipe.cpp`): builds VoidLibrary's module closure for projects that use the library directly.
`contrib/voidlibrary-migration/` contains the description used to migrate VoidLibrary itself: a native build with all modules, profiles and a smoke test. VoidLibrary upstream gained its own VBS description and CI workflow; the remaining upstream work is tracked in its own repository rather than being duplicated here.
The self-host recipe (`recipes/SelfHost/VbsSelfHostRecipe.cpp`) builds `vbs` itself without CMake and is exercised by `vbs_selfhost_tests`.
## CI matrix
The Gitea workflow at `.gitea/workflows/ci.yml` defines:
| Stage | Runner | What it does |
| --- | --- | --- |
| 1 · Requirements | `vulkan` | Verifies GCC 16, `-freflection`, CMake 4, Ninja and Git |
| 2A · Linux build | `vulkan` | Debug, RelWithDebInfo and ASan+UBSan builds; uploads binaries, SDK library and compile database |
| 3A · Linux test | `vulkan` | Full CTest for Debug/RelWithDebInfo; SDK + core suites under sanitizers; benchmark smoke on Debug |
| 2B · Windows Wine build | `windows-gcc` | Cross-builds VBS with MinGW-w64 GCC 16; uploads binaries and SDK |
| 3B · Windows Wine test | `windows-gcc` | Runs SDK/core executables under Wine; marked `continue-on-error` while the Wine-hosted suite matures |
| 4A2 · VBS installers (Linux) | `vulkan` | Self-hosted `vbs install` produces tar, sh, zip, deb, rpm, wix, dmg and nuget archives |
| 4A2 · VBS installers (Windows) | `windows-gcc` | Cross-installs Windows-target tar, zip, nuget and wix archives; non-blocking |
| 5 · Release | `vulkan` | Verifies the tag against the project version, writes `SHA256SUMS`, creates the Gitea release and uploads assets |
The Linux installer job retries once in a fresh build directory before failing. The Windows lanes exist to exercise the target toolchain and packaging path; they are not a claim of native Windows-host support.
## Release packaging
`vbs install` builds the project, imports dependencies, stages the prefix and writes the archive:
```sh
vbs install --project . --build-dir build/release --profile release --jobs 4 \
--prefix /tmp/vbs-prefix \
--package-name VoidBuildSystem --package-version 1.0.0 \
--archive dist/vbs-v1.0.0-linux-x86_64.tar \
--archive-format tar
```
The installer job repeats this for all eight formats. The release job:
1. checks that a `v*` tag matches `project(VoidBuildSystem VERSION ...)`;
2. computes `SHA256SUMS` over every artifact;
3. creates (or reuses) the Gitea release for the tag;
4. uploads each installer and the checksum file as release assets.
The release body names the commit and points readers at `SHA256SUMS`. Windows artifacts are attached when the optional Windows installer job produced them.
## Installer contents
The current root description installs the CLI binaries (`vbs`, and `vbs-registry` on POSIX). It does **not** declare `VoidBuildSdk`, `VoidBuildCore` or the SDK headers as install targets, so the 1.0.0 release archive contains those binaries plus the generated export metadata, not a complete SDK. Consumers who need the SDK should build or install the libraries explicitly.
## Verification checklist for a self-host change
:::steps
@@step[Bootstrap]
Build and run CTest with GCC 16.
@@step[Self-host test]
Run `vbs test` with `cmake` trapped on `PATH`.
@@step[Rebuild from a clean directory]
Build again with `--no-cache` and a different build directory.
@@step[Compare artifacts]
Hash `vbs`, `libVoidBuildSdk.a` and `libVoidBuildCore.a` from both stages.
@@step[Package]
Run `vbs install` for at least tar and one native format; unpack and run the binary.
:::
Next: [check the quality record and known limits](/build-system/developer/quality-and-status).
@@ -0,0 +1,174 @@
---
title: Snapshots, Scheduling and State
description: Immutable inputs, process supervision, action keys, the local CAS and remote cache, garbage collection and editor generations
section: Configuration & Execution
badge: execution
order: 2
tags: [internals, snapshots, scheduler, cas, cache, state, depfiles, watcher, editor]
updated: 2026-12-06
---
# Snapshots, Scheduling and State
This layer owns correctness for everything after graph lowering: freeze the admitted inputs, run actions against them, validate outputs, publish immutable artifacts, and record only verified success.
## Snapshot capture
A snapshot is captured after dependency resolution and before graph lowering:
- roots: conventional `src`, `source`, `include`, `tests`, `sdk`; declared include dirs inside the project; parent directories of explicit sources; prefixes of globs; custom-action and PCH inputs;
- `$GEN/` and `gen/` references are excluded from capture and validated by action dependencies instead;
- default exclusions: `.git`, `.vbs`, `build`, `.serena`, `.cache`, `.env*` (except `.env.example`), `*.pem`, `*.key`, `keys`, `WG.conf`.
Storage:
```text
<build>/.vbs/snapshots/
├── blobs/<2>/<sha256> # content-addressed file bytes, 0444
├── trees/<snapshot-id>/<logical> # materialized private tree + .sealed
├── manifests/<snapshot-id>.json
└── generated/<2>/<sha256> # sealed generated artifacts
```
### Isolation and validation
- Files are copied with `Void::FileSystem::reflink_copy_file` when the filesystem supports reflinks, otherwise a real copy. Hardlinks are never used.
- Symlinked regular files materialize as copies of the resolved target; the target path and bytes both participate in identity.
- Capture retries the whole snapshot up to five times when the tree changes concurrently. Every file is re-hashed (parallel hashing for 32+ files) and every directory membership is re-read before sealing.
- Materialization is verified; a missing tree is rebuilt up to three times.
- A failure reports `source tree remained unstable across N revalidation retries`.
`snapshot_id` is SHA-256 over the version tag, reproducibility epoch, every entry (path, mode, size, digest, symlink target), every directory membership and any lookup guards.
:::callout{type="warning" title="Lookup guards are dormant"}
The schema and `is_snapshot_fresh()` support absence/shadowing guards, but production callers do not populate queries in 1.0.0, and `is_snapshot_fresh()` is used only by tests. Treat the snapshot as a content/membership freeze, not as a fully exercised include-shadowing oracle.
:::
### Determinism
- Snapshot blobs and materialized tree files get canonical mtimes (epoch, atime 0).
- Compile/custom/shader actions receive `SOURCE_DATE_EPOCH=<profile epoch>`, `TZ=UTC`, `LC_ALL=C`.
- GCC deterministic compiles add `-frandom-seed=<object filename>`.
- Path maps rewrite the snapshot root to the project root and the profile build directory to `/vbs-build`.
- Deterministic archives use `ar rcsD`.
- Link actions receive `TZ`/`LC_ALL`; there is no canonical output mtime on linked artifacts.
## Toolchain identity
`discover_and_probe()` records:
- compiler and C/archiver paths, SHA-256 and version banner;
- target triple and sysroot;
- capability probes for C/C++ standards, reflection, prefix maps, LTO and sanitizers;
- module scanning support (GCC P1689 or Clang + `clang-scan-deps`);
- default system include dirs for Clang scanning;
- shader tools (`glslangValidator`, `slangc`, `dxc`), which are intentionally **not** part of the toolchain identity because each shader action's key includes its command line.
Probe results are cached under `<build>/.vbs/probes/` keyed by compiler identity, archiver, sysroot, OS/arch and relevant environment variables (`CPATH`, `C_INCLUDE_PATH`, `CPLUS_INCLUDE_PATH`, `LIBRARY_PATH`, `COMPILER_PATH`, `GCC_EXEC_PREFIX`, `NIX_*`). `toolchain.identity_hash` combines the probe key, version banner and target triple; `profile_identity` adds profile name, family, OS/arch, standards, LTO, sysroot, epoch, nondeterminism, options, defines and sanitizers.
Command lowering is explicit:
- `.c` uses the C driver; `.s`/`.S` use the C driver without C/C++ standard, LTO or sanitizer flags; everything else uses C++.
- Shared-library compiles add `-fPIC`.
- Each requested unsupported capability is an error, not a silent downgrade.
- Response files are emitted when the summed argv exceeds 32 KiB; the file name includes a content hash and actions reference `@file`.
## Scheduler
`execute_graph()`:
- selects the action closure of the requested enabled targets, preserving graph order;
- uses `min(selected actions, --jobs or hardware concurrency)` workers;
- takes an exclusive per-profile lock and a CAS lease for the run;
- runs each action in a new process group;
- captures bounded stdout/stderr (8 MiB each) and supports timeout/cancellation with group `SIGTERM` → grace → `SIGKILL`;
- enables child subreaper mode so escaped grandchildren are reaped;
- stops scheduling new actions after the first failure;
- requires every declared output to exist as a regular file after exit 0;
- parses depfiles and records discovered inputs with hashes;
- rejects a depfile entry whose generated producer is not an ancestor.
Different profiles can run concurrently; the CLI itself loops over requested profiles sequentially. `fail_fast` is not exposed on the CLI.
:::callout{type="warning" title="Ctrl+C is not a graceful build cancel"}
The scheduler supports stop tokens, but `vbs build` and `vbs test` do not install a `SignalWatcher` in 1.0.0. Only `vbs watch`, `vbs compdb watch` and the daemon do. An interactive Ctrl+C can kill the parent without group cleanup; use the daemon or a supervising process when clean cancellation matters.
:::
## Action keys and cache lookup
There are two keys:
1. **Graph-time key** over `vbs-action-v1`, profile identity, toolchain identity, kind, target, executable, argv, response-file content, environment, declared input paths, declared output paths, the whole snapshot id and the nondeterministic flag.
2. **Execution-time key** that additionally hashes every declared input file's bytes, so a changed upstream artifact invalidates its consumers.
A cache hit must also:
- re-verify every discovered depfile input;
- re-verify recorded output digests;
- restore missing outputs from the CAS.
Every declared output is copied to the CAS before the success record is committed. A missing or corrupt blob drops the record.
Because the key includes the whole-project snapshot id, any source edit re-keys all actions. Only a true no-op is fully cached; this is a known incrementality limit.
## State store and CAS
`StateStore::open(<build>/.vbs)` owns:
```text
.vbs/
├── cas/blobs/<2>/<sha256> # immutable, 0444
├── staging/ # transient; cleaned by recover()
├── leases/ # pid/profile/pinned blobs
├── state/state.v1.json # JSON fallback
├── state/state.v2.sqlite # Void::Sqlite backend when linked
└── state/state.lock
```
- The CMake bootstrap links `Void::Sqlite` and uses `state.v2.sqlite`; a self-hosted `vbs` built by the current `build.cpp` does not link SQLite and uses the JSON store.
- An existing JSON database is imported once into an empty SQLite store.
- Writes use the state lock; an in-memory snapshot is reused while the database stat fingerprint is unchanged.
- `recover()` removes uncommitted staging, dead leases, and action records whose blobs fail verification. It never invents success.
- `gc()` removes blobs not pinned by a record or live lease. `--max-bytes` is a **quota check**: if pinned data exceeds it, GC fails; there is no LRU eviction.
## Remote cache
The remote CAS protocol is described in [Remote cache and workers](/build-system/consumer/remote-ci). Internally:
- only local misses consult the remote cache;
- only cacheable, deterministic actions participate;
- remote keys normalize `${SNAPSHOT}`, `${PROFILE}`, `${BUILD}` and `${PROJECT}` prefixes and reduce external executables to basenames;
- downloaded blobs are SHA-256 verified before entering the local CAS;
- uploads happen after local commit and are best-effort;
- `--no-cache` disables reads but not writes;
- `--offline` does not disable remote-cache traffic.
## Watchers and editor generations
`InotifyWatcher` (Linux inotify, Windows backend) coalesces bursts with a 40 ms debounce. `run_watch_loop` reconciles on events, a periodic tick, overflow/rescan, or a changed editor selection.
Two modes:
| Mode | Behavior |
| --- | --- |
| `MetadataOnly` | Compiles/evaluates the descriptor, probes the toolchain, lowers the graph, publishes the compilation database and stops. No builds, no providers, no fetch/lock writes, snapshot without materialization. |
| `FullBuild` | Additionally executes the selected action closure. Foreign provider metadata is read-only; stale providers are reported, not rebuilt. |
Editor selection is governed by a project-level ticket in `<project>/.vbs/editor_selection.json`:
- a ticket is reserved before descriptor compilation;
- a build publishes its generation before executing actions, so a compile failure does not hide fresh flags;
- a later ticket wins; a late completion with an older ticket cannot overwrite it;
- each generation is immutable under `profiles/<p>/editor/generations/<id>/`;
- the profile pointer is swapped atomically; the project-root alias is only touched when absent or VBS-owned;
- stale/invalid status keeps the last valid database identifiable.
## Known execution limits
- No snapshot in the daemon build path; daemon keys differ from CLI keys.
- No graceful `SIGINT` handling for `vbs build`/`vbs test`.
- Whole-snapshot action keys prevent single-file incremental reuse.
- Lookup guards and freshness checks are not exercised by production builds.
- `ModuleScan` is not scheduled as a DAG action.
- PCH and MSan/LSan lack capability probes.
- Remote downloads are buffered in memory rather than streamed.