Files
Build-System/docs/build-system/developer/snapshots-and-execution.md
T

175 lines
9.9 KiB
Markdown

---
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.