Files
Build-System/src/State/StateStore.cpp
T
faumaray e990f44037
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / signing-openssl-gcc16 (push) Failing after 10s
feat(state,registry): back StateStore with Void::Sqlite when available and filter audit queries
2026-12-04 01:02:18 +03:00

1178 lines
43 KiB
C++

#include <Void/Build/State/StateStore.hpp>
#include <Void/Build/Platform/FileOps.hpp>
#include <Void/Build/Util/Json.hpp>
#include <Void/Build/Util/Sha256.hpp>
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <csignal>
#include <format>
#include <mutex>
#include <sys/stat.h>
#include <unistd.h>
#include <utility>
namespace Void::Build::State {
namespace {
std::atomic<std::uint64_t> g_lease_seq{0};
Void::Result::Error make_error(Void::System::SystemErrorCode code, std::string msg, int err = 0) {
return Void::System::make_system_error(code, std::move(msg), err);
}
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'); });
}
bool pid_is_alive(pid_t pid) noexcept {
if (pid <= 0) {
return false;
}
if (::kill(pid, 0) == 0) {
return true;
}
return errno != ESRCH;
}
std::string serialize_action(const ActionSuccessRecord &rec) {
using Util::json_array;
using Util::json_quote;
std::string out = "{\"action_key\":" + json_quote(rec.action_key) +
",\"profile_identity\":" + json_quote(rec.profile_identity) +
",\"target_name\":" + json_quote(rec.target_name) +
",\"recorded_epoch\":" + std::to_string(rec.recorded_epoch) +
",\"outputs\":{";
bool first = true;
for (const auto &[path, ref] : rec.outputs) {
if (!first) {
out += ',';
}
first = false;
out += json_quote(path) + ":{\"sha256\":" + json_quote(ref.sha256) +
",\"size\":" + std::to_string(ref.size) + ",\"mode\":" + std::to_string(ref.mode) +
'}';
}
out += "},\"discovered_inputs\":{";
first = true;
for (const auto &[path, digest] : rec.discovered_inputs) {
if (!first) {
out += ',';
}
first = false;
out += json_quote(path) + ':' + json_quote(digest);
}
out += "},\"lookup_guards\":";
out += json_array(rec.lookup_guards, [](const Snapshot::LookupGuard &g) {
return "{\"search_roots\":" + json_array(g.search_roots, json_quote) +
",\"lookup_name\":" + json_quote(g.lookup_name) +
",\"matched_root_index\":" + std::to_string(g.matched_root_index) +
",\"matched_sha256\":" + json_quote(g.matched_sha256) + '}';
});
out += '}';
return out;
}
std::string serialize_generation(const GraphGenerationRecord &gen) {
using Util::json_quote;
return "{\"generation_id\":" + json_quote(gen.generation_id) +
",\"profile_name\":" + json_quote(gen.profile_name) +
",\"profile_identity\":" + json_quote(gen.profile_identity) +
",\"snapshot_id\":" + json_quote(gen.snapshot_id) +
",\"status\":" + json_quote(gen.status) +
",\"diagnostic\":" + json_quote(gen.diagnostic) +
",\"sequence\":" + std::to_string(gen.sequence) + '}';
}
using JsonVal = Void::Json::Strict::Value;
const JsonVal *find_key(const JsonVal::Object &obj, const std::string &key) {
const auto it = obj.find(key);
return it == obj.end() ? nullptr : &it->second;
}
std::optional<std::string> get_str(const JsonVal::Object &obj, const std::string &key) {
const auto *v = find_key(obj, key);
if (!v) {
return std::nullopt;
}
const auto *s = std::get_if<std::string>(&v->value);
return s ? std::optional<std::string>{*s} : std::nullopt;
}
std::optional<std::int64_t> get_i64(const JsonVal::Object &obj, const std::string &key) {
const auto *v = find_key(obj, key);
if (!v) {
return std::nullopt;
}
const auto *i = std::get_if<std::int64_t>(&v->value);
return i ? std::optional<std::int64_t>{*i} : std::nullopt;
}
} // namespace
LeaseHandle::~LeaseHandle() noexcept { release(); }
LeaseHandle::LeaseHandle(LeaseHandle &&other) noexcept
: lease_id{std::move(other.lease_id)}, lease_file{std::exchange(other.lease_file, {})} {}
LeaseHandle &LeaseHandle::operator=(LeaseHandle &&other) noexcept {
if (this != &other) {
release();
lease_id = std::move(other.lease_id);
lease_file = std::exchange(other.lease_file, {});
}
return *this;
}
void LeaseHandle::release() noexcept {
if (!lease_file.empty()) {
std::error_code ec;
std::filesystem::remove(lease_file, ec);
lease_file.clear();
}
}
struct StateStore::CacheState {
struct StatFingerprint {
std::uint64_t dev{0};
std::uint64_t ino{0};
std::uint64_t size{0};
std::int64_t mtime_sec{0};
std::int64_t mtime_nsec{0};
bool operator==(const StatFingerprint &) const noexcept = default;
};
static std::optional<StatFingerprint> stat_file(const std::filesystem::path &p) noexcept {
struct stat st{};
if (::stat(p.c_str(), &st) != 0) {
return std::nullopt;
}
return StatFingerprint{
static_cast<std::uint64_t>(st.st_dev), static_cast<std::uint64_t>(st.st_ino),
static_cast<std::uint64_t>(st.st_size), static_cast<std::int64_t>(st.st_mtim.tv_sec),
static_cast<std::int64_t>(st.st_mtim.tv_nsec)};
}
std::mutex mutex;
bool valid{false};
StatFingerprint fp{};
DatabaseSnapshot db;
};
StateStore::StateStore(std::filesystem::path root)
: root_{std::move(root)}, cas_dir_{root_ / "cas" / "blobs"}, staging_dir_{root_ / "staging"},
leases_dir_{root_ / "leases"}, db_file_{root_ / "state" / "state.v1.json"},
sqlite_file_{root_ / "state" / "state.v2.sqlite"}, lock_file_{root_ / "state" / "state.lock"},
cache_{std::make_shared<CacheState>()} {}
Void::Result::Result<StateStore, Void::Result::Error>
StateStore::open(const std::filesystem::path &vbs_dir) {
StateStore store{vbs_dir};
std::error_code ec;
std::filesystem::create_directories(store.cas_dir_, ec);
std::filesystem::create_directories(store.staging_dir_, ec);
std::filesystem::create_directories(store.leases_dir_, ec);
std::filesystem::create_directories(store.db_file_.parent_path(), ec);
if (ec) {
return std::unexpected{
make_error(Void::System::map_errno_to_system_code(ec.value()),
std::format("StateStore::open: cannot create directories under '{}': {}",
vbs_dir.string(), ec.message()),
ec.value())};
}
auto lock = Platform::FileLock::acquire(store.lock_file_, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
#if defined(VBS_HAS_VOID_SQLITE)
// Durable transactional action cache backed by Void::Sqlite (Track E4). The legacy JSON
// database is imported once when it exists and the SQLite database is still empty.
auto sqlite = Void::Sqlite::Database::open(store.sqlite_file_);
if (!sqlite) {
return std::unexpected{sqlite.error()};
}
store.sqlite_ = std::move(*sqlite);
if (auto schema = store.sqlite_->exec(
"CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);"
"CREATE TABLE IF NOT EXISTS actions(action_key TEXT PRIMARY KEY, payload TEXT NOT "
"NULL);"
"CREATE TABLE IF NOT EXISTS generations(sequence INTEGER PRIMARY KEY, payload TEXT "
"NOT NULL);");
!schema) {
return std::unexpected{schema.error()};
}
auto action_count = store.sqlite_->prepare("SELECT COUNT(*) FROM actions");
if (!action_count) {
return std::unexpected{action_count.error()};
}
auto has_row = action_count->step();
if (!has_row) {
return std::unexpected{has_row.error()};
}
const auto counted = *has_row ? action_count->column_int(0) : 0;
if (counted == 0 && std::filesystem::exists(store.db_file_, ec)) {
auto legacy = store.load_json_db_locked();
if (!legacy) {
return std::unexpected{legacy.error()};
}
if (auto imported = store.save_sqlite_db_locked(*legacy); !imported) {
return std::unexpected{imported.error()};
}
}
return store;
#else
if (std::filesystem::exists(store.db_file_, ec)) {
auto loaded = store.load_db_locked();
if (!loaded) {
return std::unexpected{loaded.error()};
}
} else {
DatabaseSnapshot initial;
auto saved = store.save_db_locked(initial);
if (!saved) {
return std::unexpected{saved.error()};
}
}
return store;
#endif
}
std::filesystem::path StateStore::cas_blob_path(std::string_view sha256) const {
if (sha256.size() < 2) {
return cas_dir_ / std::string{sha256};
}
return cas_dir_ / std::string{sha256.substr(0, 2)} / std::string{sha256};
}
#if defined(VBS_HAS_VOID_SQLITE)
namespace {
Void::Result::Result<std::string, Void::Result::Error>
read_column_text(const Void::Sqlite::RowView &row, int column) {
auto text = row.get_text(column);
if (!text) {
return std::unexpected{text.error()};
}
return std::move(*text);
}
} // namespace
#endif
Void::Result::Result<StateStore::DatabaseSnapshot, Void::Result::Error>
StateStore::load_db_locked() const {
#if defined(VBS_HAS_VOID_SQLITE)
if (sqlite_) {
DatabaseSnapshot snap;
auto meta = sqlite_->prepare("SELECT key, value FROM meta");
if (!meta) {
return std::unexpected{meta.error()};
}
while (true) {
auto has_row = meta->step();
if (!has_row) {
return std::unexpected{has_row.error()};
}
if (!*has_row) {
break;
}
const auto row = meta->current_row();
if (!row) {
return std::unexpected{row.error()};
}
auto key = read_column_text(*row, 0);
auto value = read_column_text(*row, 1);
if (!key || !value) {
return std::unexpected{key ? value.error() : key.error()};
}
if (*key == "schema_version") {
snap.schema_version = std::stoi(*value);
} else if (*key == "next_sequence") {
snap.next_sequence = std::stoull(*value);
}
}
auto actions = sqlite_->prepare("SELECT payload FROM actions");
if (!actions) {
return std::unexpected{actions.error()};
}
while (true) {
auto has_row = actions->step();
if (!has_row) {
return std::unexpected{has_row.error()};
}
if (!*has_row) {
break;
}
const auto action_row = actions->current_row();
if (!action_row) {
return std::unexpected{action_row.error()};
}
auto payload = read_column_text(*action_row, 0);
if (!payload) {
return std::unexpected{payload.error()};
}
auto records = parse_database_snapshot(
"{\"schema_version\":1,\"actions\":[" + *payload + "]}", "sqlite actions");
if (!records) {
return std::unexpected{records.error()};
}
if (records->actions.empty()) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: empty SQLite action payload")};
}
auto record = records->actions.begin();
snap.actions[record->first] = std::move(record->second);
}
auto generations = sqlite_->prepare("SELECT payload FROM generations ORDER BY sequence");
if (!generations) {
return std::unexpected{generations.error()};
}
while (true) {
auto has_row = generations->step();
if (!has_row) {
return std::unexpected{has_row.error()};
}
if (!*has_row) {
break;
}
const auto generation_row = generations->current_row();
if (!generation_row) {
return std::unexpected{generation_row.error()};
}
auto payload = read_column_text(*generation_row, 0);
if (!payload) {
return std::unexpected{payload.error()};
}
auto parsed = Void::Json::Strict::parse(*payload);
if (!parsed) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: corrupt SQLite generation payload")};
}
const auto *obj = std::get_if<JsonVal::Object>(&parsed->value);
if (!obj) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: generation payload must be object")};
}
GraphGenerationRecord gen;
gen.generation_id = get_str(*obj, "generation_id").value_or("");
gen.profile_name = get_str(*obj, "profile_name").value_or("");
gen.profile_identity = get_str(*obj, "profile_identity").value_or("");
gen.snapshot_id = get_str(*obj, "snapshot_id").value_or("");
gen.status = get_str(*obj, "status").value_or("invalid");
gen.diagnostic = get_str(*obj, "diagnostic").value_or("");
gen.sequence = static_cast<std::uint64_t>(get_i64(*obj, "sequence").value_or(0));
snap.generations.push_back(std::move(gen));
}
return snap;
}
#endif
return load_json_db_locked();
}
Void::Result::Result<StateStore::DatabaseSnapshot, Void::Result::Error>
StateStore::parse_database_snapshot(std::string_view content, std::string_view origin) {
auto parsed = Void::Json::Strict::parse(content);
if (!parsed) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("StateStore: corrupt state database '{}' (JSON parse failure)", origin))};
}
const auto *root_obj = std::get_if<JsonVal::Object>(&parsed->value);
if (!root_obj) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: root state must be a JSON object")};
}
const auto version = get_i64(*root_obj, "schema_version");
if (!version) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: missing schema_version")};
}
if (*version > kStateSchemaVersion) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("StateStore: unsupported newer schema version {} (supported <= {})",
*version, kStateSchemaVersion))};
}
if (*version < 1) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: invalid schema version")};
}
DatabaseSnapshot snap;
snap.schema_version = static_cast<int>(*version);
snap.next_sequence =
static_cast<std::uint64_t>(get_i64(*root_obj, "next_sequence").value_or(1));
if (const auto *actions_val = find_key(*root_obj, "actions")) {
const auto *arr = std::get_if<JsonVal::Array>(&actions_val->value);
if (!arr) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: corrupt actions array")};
}
for (const auto &item : *arr) {
const auto *obj = std::get_if<JsonVal::Object>(&item.value);
if (!obj) {
continue;
}
ActionSuccessRecord rec;
rec.action_key = get_str(*obj, "action_key").value_or("");
rec.profile_identity = get_str(*obj, "profile_identity").value_or("");
rec.target_name = get_str(*obj, "target_name").value_or("");
rec.recorded_epoch = get_i64(*obj, "recorded_epoch").value_or(0);
if (const auto *outs = find_key(*obj, "outputs")) {
if (const auto *oobj = std::get_if<JsonVal::Object>(&outs->value)) {
for (const auto &[path, refv] : *oobj) {
if (const auto *robj = std::get_if<JsonVal::Object>(&refv.value)) {
BlobRef ref;
ref.sha256 = get_str(*robj, "sha256").value_or("");
ref.size =
static_cast<std::uint64_t>(get_i64(*robj, "size").value_or(0));
ref.mode =
static_cast<std::uint32_t>(get_i64(*robj, "mode").value_or(0644));
rec.outputs[path] = std::move(ref);
}
}
}
}
if (const auto *deps = find_key(*obj, "discovered_inputs")) {
if (const auto *dobj = std::get_if<JsonVal::Object>(&deps->value)) {
for (const auto &[path, dv] : *dobj) {
if (const auto *s = std::get_if<std::string>(&dv.value)) {
rec.discovered_inputs[path] = *s;
}
}
}
}
if (const auto *guards = find_key(*obj, "lookup_guards")) {
if (const auto *garr = std::get_if<JsonVal::Array>(&guards->value)) {
for (const auto &gv : *garr) {
if (const auto *gobj = std::get_if<JsonVal::Object>(&gv.value)) {
Snapshot::LookupGuard g;
g.lookup_name = get_str(*gobj, "lookup_name").value_or("");
g.matched_root_index =
static_cast<int>(get_i64(*gobj, "matched_root_index").value_or(-1));
g.matched_sha256 = get_str(*gobj, "matched_sha256").value_or("");
if (const auto *sr = find_key(*gobj, "search_roots")) {
if (const auto *sarr = std::get_if<JsonVal::Array>(&sr->value)) {
for (const auto &rv : *sarr) {
if (const auto *rs = std::get_if<std::string>(&rv.value)) {
g.search_roots.push_back(*rs);
}
}
}
}
rec.lookup_guards.push_back(std::move(g));
}
}
}
}
if (!rec.action_key.empty()) {
snap.actions[rec.action_key] = std::move(rec);
}
}
}
if (const auto *gens_val = find_key(*root_obj, "generations")) {
const auto *arr = std::get_if<JsonVal::Array>(&gens_val->value);
if (!arr) {
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: corrupt generations array")};
}
for (const auto &item : *arr) {
const auto *obj = std::get_if<JsonVal::Object>(&item.value);
if (!obj) {
continue;
}
GraphGenerationRecord gen;
gen.generation_id = get_str(*obj, "generation_id").value_or("");
gen.profile_name = get_str(*obj, "profile_name").value_or("");
gen.profile_identity = get_str(*obj, "profile_identity").value_or("");
gen.snapshot_id = get_str(*obj, "snapshot_id").value_or("");
gen.status = get_str(*obj, "status").value_or("invalid");
gen.diagnostic = get_str(*obj, "diagnostic").value_or("");
gen.sequence = static_cast<std::uint64_t>(get_i64(*obj, "sequence").value_or(0));
snap.generations.push_back(std::move(gen));
}
}
return snap;
}
Void::Result::Result<StateStore::DatabaseSnapshot, Void::Result::Error>
StateStore::load_json_db_locked() const {
const auto cur_fp = CacheState::stat_file(db_file_);
if (cur_fp && cache_) {
std::lock_guard lk{cache_->mutex};
if (cache_->valid && cache_->fp == *cur_fp) {
return cache_->db;
}
}
auto content = Void::FileSystem::read_file_bounded(db_file_, {128ULL * 1024ULL * 1024ULL});
if (!content) {
return std::unexpected{content.error()};
}
if (!Util::is_valid_utf8(*content)) {
return std::unexpected{
make_error(Void::System::SystemErrorCode::io_error,
std::format("StateStore: corrupt state database '{}' (invalid UTF-8)",
db_file_.string()))};
}
auto snap = parse_database_snapshot(*content, db_file_.string());
if (!snap) {
return std::unexpected{snap.error()};
}
if (cur_fp && cache_) {
std::lock_guard lk{cache_->mutex};
cache_->db = *snap;
cache_->fp = *cur_fp;
cache_->valid = true;
}
return snap;
}
Void::Result::Result<void, Void::Result::Error>
StateStore::save_sqlite_db_locked(const DatabaseSnapshot &db) const {
#if defined(VBS_HAS_VOID_SQLITE)
if (!sqlite_) {
return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument,
"StateStore: SQLite database is not open")};
}
auto transaction = sqlite_->begin();
if (!transaction) {
return std::unexpected{transaction.error()};
}
if (auto cleared = sqlite_->exec("DELETE FROM actions; DELETE FROM generations;"); !cleared) {
(void)transaction->rollback_checked();
return std::unexpected{cleared.error()};
}
auto upsert_meta = sqlite_->prepare("INSERT INTO meta(key, value) VALUES(?1, ?2) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value");
auto insert_action =
sqlite_->prepare("INSERT INTO actions(action_key, payload) VALUES(?1, ?2)");
auto insert_generation =
sqlite_->prepare("INSERT INTO generations(sequence, payload) VALUES(?1, ?2)");
if (!upsert_meta || !insert_action || !insert_generation) {
(void)transaction->rollback_checked();
return std::unexpected{!(upsert_meta) ? upsert_meta.error()
: !(insert_action) ? insert_action.error()
: insert_generation.error()};
}
const auto bind_meta = [&](std::string_view key, const std::string &value) -> bool {
upsert_meta->bind(1, key).bind(2, value);
const auto ran = upsert_meta->step();
upsert_meta->reset();
// step() reports whether a row was produced; SQLITE_DONE (no row) is success here.
return ran.has_value();
};
if (!bind_meta("schema_version", std::to_string(db.schema_version)) ||
!bind_meta("next_sequence", std::to_string(db.next_sequence))) {
(void)transaction->rollback_checked();
return std::unexpected{make_error(Void::System::SystemErrorCode::io_error,
"StateStore: failed writing SQLite metadata")};
}
for (const auto &[key, record] : db.actions) {
insert_action->bind(1, key).bind(2, serialize_action(record));
auto ran = insert_action->step();
insert_action->reset();
if (!ran) {
(void)transaction->rollback_checked();
return std::unexpected{ran.error()};
}
}
for (const auto &generation : db.generations) {
insert_generation->bind(1, static_cast<std::int64_t>(generation.sequence))
.bind(2, serialize_generation(generation));
auto ran = insert_generation->step();
insert_generation->reset();
if (!ran) {
(void)transaction->rollback_checked();
return std::unexpected{ran.error()};
}
}
auto committed = transaction->commit();
if (!committed) {
return std::unexpected{committed.error()};
}
return {};
#else
static_cast<void>(db);
return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported,
"StateStore: built without Void::Sqlite")};
#endif
}
Void::Result::Result<void, Void::Result::Error>
StateStore::save_db_locked(const DatabaseSnapshot &db) const {
#if defined(VBS_HAS_VOID_SQLITE)
if (sqlite_) {
return save_sqlite_db_locked(db);
}
#endif
std::string json = "{\"schema_version\":" + std::to_string(db.schema_version) +
",\"next_sequence\":" + std::to_string(db.next_sequence) + ",\"actions\":[";
bool first = true;
for (const auto &[key, rec] : db.actions) {
if (!first) {
json += ',';
}
first = false;
json += serialize_action(rec);
}
json += "],\"generations\":[";
first = true;
for (const auto &gen : db.generations) {
if (!first) {
json += ',';
}
first = false;
json += serialize_generation(gen);
}
json += "]}\n";
auto wrote = Platform::atomic_write_file(db_file_, json, true);
if (!wrote) {
return wrote;
}
if (cache_) {
std::lock_guard lk{cache_->mutex};
const auto new_fp = CacheState::stat_file(db_file_);
if (new_fp) {
cache_->db = db;
cache_->fp = *new_fp;
cache_->valid = true;
} else {
cache_->valid = false;
}
}
return {};
}
Void::Result::Result<BlobRef, Void::Result::Error>
StateStore::store_blob_from_file(const std::filesystem::path &file_path) {
auto meta = Platform::stat_lstat(file_path);
if (!meta) {
return std::unexpected{meta.error()};
}
if (!meta->exists || !meta->is_regular) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::not_found,
std::format("StateStore: cannot store non-regular file '{}'", file_path.string()))};
}
const auto stage_path =
staging_dir_ / std::format("blob_{}_{}.stage", static_cast<long long>(::getpid()),
g_lease_seq.fetch_add(1, std::memory_order_relaxed));
auto copied = Platform::copy_isolated(file_path, stage_path, meta->mode);
if (!copied) {
return std::unexpected{copied.error()};
}
auto digest = Util::sha256_file_hex(stage_path);
std::error_code ec;
if (!digest) {
std::filesystem::remove(stage_path, ec);
return std::unexpected{digest.error()};
}
const auto final_path = cas_blob_path(*digest);
std::filesystem::create_directories(final_path.parent_path(), ec);
if (std::filesystem::exists(final_path, ec)) {
// Verify existing blob integrity before deduplicating.
auto existing_ok = verify_blob(*digest);
if (existing_ok && *existing_ok) {
std::filesystem::remove(stage_path, ec);
} else {
(void)::chmod(final_path.c_str(), 0644);
std::filesystem::rename(stage_path, final_path, ec);
(void)::chmod(final_path.c_str(), 0444);
}
} else {
(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, ec)) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("StateStore: failed publishing CAS blob '{}'", *digest))};
}
}
(void)Platform::fsync_directory(final_path.parent_path());
}
BlobRef ref;
ref.sha256 = std::move(*digest);
ref.size = meta->size;
ref.mode = meta->mode & 0777u;
return ref;
}
Void::Result::Result<bool, Void::Result::Error>
StateStore::verify_blob(std::string_view sha256) const {
if (!is_valid_sha256_hex(sha256)) {
return false;
}
const auto path = cas_blob_path(sha256);
auto meta = Platform::stat_lstat(path);
if (!meta) {
return std::unexpected{meta.error()};
}
if (!meta->exists || !meta->is_regular) {
return false;
}
auto actual = Util::sha256_file_hex(path);
if (!actual) {
return std::unexpected{actual.error()};
}
return *actual == sha256;
}
Void::Result::Result<void, Void::Result::Error>
StateStore::materialize_blob(const BlobRef &ref, const std::filesystem::path &destination) const {
auto ok = verify_blob(ref.sha256);
if (!ok) {
return std::unexpected{ok.error()};
}
if (!*ok) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::io_error,
std::format("StateStore: CAS blob '{}' is missing or corrupted", ref.sha256))};
}
auto copied = Platform::copy_isolated(cas_blob_path(ref.sha256), destination, ref.mode);
if (!copied) {
return std::unexpected{copied.error()};
}
return {};
}
void StateStore::configure_remote_cache(std::optional<RemoteCacheConfig> config) {
if (config && !config->url.empty()) {
remote_.emplace(std::move(*config));
} else {
remote_.reset();
}
}
Void::Result::Result<std::optional<std::string>, Void::Result::Error>
StateStore::fetch_remote_action(std::string_view action_key) const {
if (!remote_) {
return std::optional<std::string>{};
}
return remote_->get_action(action_key);
}
Void::Result::Result<void, Void::Result::Error>
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<void, Void::Result::Error>
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<bool, Void::Result::Error>
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<std::optional<ActionSuccessRecord>, Void::Result::Error>
StateStore::lookup_action(std::string_view action_key) const {
std::optional<ActionSuccessRecord> found;
{
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
if (!lock) {
return std::unexpected{lock.error()};
}
const auto cur_fp = CacheState::stat_file(db_file_);
bool served_from_cache = false;
if (cur_fp && cache_) {
std::lock_guard lk{cache_->mutex};
if (cache_->valid && cache_->fp == *cur_fp) {
if (const auto it = cache_->db.actions.find(action_key);
it != cache_->db.actions.end()) {
found = it->second;
}
served_from_cache = true;
}
}
if (!served_from_cache) {
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
if (const auto it = db->actions.find(action_key); it != db->actions.end()) {
found = it->second;
}
}
}
if (!found) {
return std::nullopt;
}
// Verify every referenced CAS blob still exists and is intact.
for (const auto &[out_path, ref] : found->outputs) {
auto ok = verify_blob(ref.sha256);
if (!ok || !*ok) {
return std::nullopt;
}
}
return found;
}
Void::Result::Result<void, Void::Result::Error>
StateStore::record_action_success(const ActionSuccessRecord &record) {
// Publication invariant: all output blobs MUST be present and verified before commit.
for (const auto &[out_path, ref] : record.outputs) {
auto ok = verify_blob(ref.sha256);
if (!ok || !*ok) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::invalid_argument,
std::format(
"StateStore: refusing to commit action '{}' referencing unverified blob '{}'",
record.action_key, ref.sha256))};
}
}
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
db->actions[record.action_key] = record;
return save_db_locked(*db);
}
Void::Result::Result<void, Void::Result::Error>
StateStore::record_generation(const GraphGenerationRecord &generation) {
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
GraphGenerationRecord copy = generation;
copy.sequence = db->next_sequence++;
db->generations.push_back(std::move(copy));
// Keep bounded recent history per store.
if (db->generations.size() > 512) {
db->generations.erase(db->generations.begin(),
db->generations.begin() +
static_cast<std::ptrdiff_t>(db->generations.size() - 512));
}
return save_db_locked(*db);
}
Void::Result::Result<std::vector<GraphGenerationRecord>, Void::Result::Error>
StateStore::list_generations(std::optional<std::string_view> profile_name) const {
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
if (!lock) {
return std::unexpected{lock.error()};
}
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
if (!profile_name) {
return db->generations;
}
std::vector<GraphGenerationRecord> filtered;
for (const auto &g : db->generations) {
if (g.profile_name == *profile_name) {
filtered.push_back(g);
}
}
return filtered;
}
Void::Result::Result<LeaseHandle, Void::Result::Error>
StateStore::acquire_lease(std::string_view profile_name,
const std::set<std::string> &pinned_blobs) {
using Util::json_array;
using Util::json_quote;
const auto seq = g_lease_seq.fetch_add(1, std::memory_order_relaxed);
const auto pid = static_cast<long long>(::getpid());
LeaseHandle handle;
handle.lease_id = std::format("lease_{}_{}", pid, seq);
handle.lease_file = leases_dir_ / (handle.lease_id + ".json");
std::string payload = "{\"pid\":" + std::to_string(pid) +
",\"profile\":" + json_quote(profile_name) +
",\"blobs\":" + json_array(pinned_blobs, json_quote) + "}\n";
auto written = Platform::atomic_write_file(handle.lease_file, payload, false);
if (!written) {
return std::unexpected{written.error()};
}
return handle;
}
Void::Result::Result<std::size_t, Void::Result::Error> StateStore::recover() {
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
std::size_t cleaned = 0;
std::error_code ec;
// 1. Remove uncommitted staging files inside managed staging directory only.
if (std::filesystem::is_directory(staging_dir_, ec)) {
for (const auto &entry : std::filesystem::directory_iterator(staging_dir_, ec)) {
std::filesystem::remove_all(entry.path(), ec);
if (!ec) {
++cleaned;
}
}
}
// 2. Reap dead-PID leases.
if (std::filesystem::is_directory(leases_dir_, ec)) {
for (const auto &entry : std::filesystem::directory_iterator(leases_dir_, ec)) {
if (!entry.is_regular_file()) {
continue;
}
auto content = Void::FileSystem::read_file(entry.path());
if (!content) {
continue;
}
auto parsed = Void::Json::Strict::parse(*content);
if (!parsed) {
std::filesystem::remove(entry.path(), ec);
++cleaned;
continue;
}
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
const auto pid = get_i64(*obj, "pid").value_or(0);
if (!pid_is_alive(static_cast<pid_t>(pid))) {
std::filesystem::remove(entry.path(), ec);
++cleaned;
}
}
}
}
// 3. Validate DB parses cleanly; drop action records whose CAS blobs are missing/corrupt.
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
bool dirty = false;
for (auto it = db->actions.begin(); it != db->actions.end();) {
bool valid = true;
for (const auto &[out_path, ref] : it->second.outputs) {
auto ok = verify_blob(ref.sha256);
if (!ok || !*ok) {
valid = false;
break;
}
}
if (!valid) {
it = db->actions.erase(it);
dirty = true;
++cleaned;
} else {
++it;
}
}
if (dirty) {
auto saved = save_db_locked(*db);
if (!saved) {
return std::unexpected{saved.error()};
}
}
return cleaned;
}
Void::Result::Result<GcStats, Void::Result::Error> StateStore::gc(std::uint64_t max_cache_bytes) {
GcStats stats;
auto cleaned_res = recover();
if (!cleaned_res) {
return std::unexpected{cleaned_res.error()};
}
stats.cleaned_staging_files = *cleaned_res;
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Exclusive);
if (!lock) {
return std::unexpected{lock.error()};
}
auto db = load_db_locked();
if (!db) {
return std::unexpected{db.error()};
}
std::set<std::string> pinned;
for (const auto &[key, rec] : db->actions) {
for (const auto &[out, ref] : rec.outputs) {
pinned.insert(ref.sha256);
}
}
// Collect blobs pinned by live leases.
std::error_code ec;
if (std::filesystem::is_directory(leases_dir_, ec)) {
for (const auto &entry : std::filesystem::directory_iterator(leases_dir_, ec)) {
auto content = Void::FileSystem::read_file(entry.path());
if (!content) {
continue;
}
auto parsed = Void::Json::Strict::parse(*content);
if (!parsed) {
continue;
}
if (const auto *obj = std::get_if<JsonVal::Object>(&parsed->value)) {
const auto pid = get_i64(*obj, "pid").value_or(0);
if (!pid_is_alive(static_cast<pid_t>(pid))) {
continue;
}
if (const auto *blobs = find_key(*obj, "blobs")) {
if (const auto *arr = std::get_if<JsonVal::Array>(&blobs->value)) {
for (const auto &bv : *arr) {
if (const auto *s = std::get_if<std::string>(&bv.value)) {
pinned.insert(*s);
}
}
}
}
}
}
}
// Remove unpinned blobs inside cas_dir_ ONLY.
std::uint64_t retained_bytes = 0;
if (std::filesystem::is_directory(cas_dir_, ec)) {
for (const auto &bucket : std::filesystem::directory_iterator(cas_dir_, ec)) {
if (!bucket.is_directory()) {
continue;
}
for (const auto &entry : std::filesystem::directory_iterator(bucket.path(), ec)) {
if (!entry.is_regular_file()) {
continue;
}
const std::string sha = entry.path().filename().string();
const auto fsize = entry.file_size(ec);
if (!pinned.contains(sha)) {
(void)::chmod(entry.path().c_str(), 0644);
std::filesystem::remove(entry.path(), ec);
if (!ec) {
++stats.removed_blobs;
stats.freed_bytes += fsize;
}
} else {
++stats.retained_blobs;
retained_bytes += fsize;
}
}
}
}
if (max_cache_bytes > 0 && retained_bytes > max_cache_bytes) {
return std::unexpected{make_error(
Void::System::SystemErrorCode::limit_exceeded,
std::format(
"StateStore::gc: active pinned cache size ({} bytes) exceeds quota ({} bytes)",
retained_bytes, max_cache_bytes))};
}
return stats;
}
std::size_t StateStore::recorded_action_count() const {
auto lock = Platform::FileLock::acquire(lock_file_, Platform::LockMode::Shared);
if (!lock) {
return 0;
}
auto db = load_db_locked();
return db ? db->actions.size() : 0;
}
} // namespace Void::Build::State