#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Build::State { namespace { std::atomic 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 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(&v->value); return s ? std::optional{*s} : std::nullopt; } std::optional 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(&v->value); return i ? std::optional{*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 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(st.st_dev), static_cast(st.st_ino), static_cast(st.st_size), static_cast(st.st_mtim.tv_sec), static_cast(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"}, lock_file_{root_ / "state" / "state.lock"}, cache_{std::make_shared()} {} Void::Result::Result 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 (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; } 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}; } Void::Result::Result StateStore::load_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 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)", db_file_.string()))}; } const auto *root_obj = std::get_if(&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(*version); snap.next_sequence = static_cast(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(&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(&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(&outs->value)) { for (const auto &[path, refv] : *oobj) { if (const auto *robj = std::get_if(&refv.value)) { BlobRef ref; ref.sha256 = get_str(*robj, "sha256").value_or(""); ref.size = static_cast(get_i64(*robj, "size").value_or(0)); ref.mode = static_cast(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(&deps->value)) { for (const auto &[path, dv] : *dobj) { if (const auto *s = std::get_if(&dv.value)) { rec.discovered_inputs[path] = *s; } } } } if (const auto *guards = find_key(*obj, "lookup_guards")) { if (const auto *garr = std::get_if(&guards->value)) { for (const auto &gv : *garr) { if (const auto *gobj = std::get_if(&gv.value)) { Snapshot::LookupGuard g; g.lookup_name = get_str(*gobj, "lookup_name").value_or(""); g.matched_root_index = static_cast(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(&sr->value)) { for (const auto &rv : *sarr) { if (const auto *rs = std::get_if(&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(&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(&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(get_i64(*obj, "sequence").value_or(0)); snap.generations.push_back(std::move(gen)); } } 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 StateStore::save_db_locked(const DatabaseSnapshot &db) const { 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 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(::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 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 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 config) { if (config && !config->url.empty()) { remote_.emplace(std::move(*config)); } else { remote_.reset(); } } Void::Result::Result, Void::Result::Error> StateStore::fetch_remote_action(std::string_view action_key) const { if (!remote_) { return std::optional{}; } return remote_->get_action(action_key); } Void::Result::Result StateStore::publish_remote_action(std::string_view action_key, std::string_view json) const { if (!remote_) { return {}; } return remote_->put_action(action_key, json); } Void::Result::Result StateStore::publish_remote_blob(std::string_view sha256) const { if (!remote_) { return {}; } if (!is_valid_sha256_hex(sha256)) { return std::unexpected{make_error(Void::System::SystemErrorCode::invalid_argument, "StateStore: invalid CAS blob digest")}; } auto bytes = Void::FileSystem::read_file(cas_blob_path(sha256)); if (!bytes) { return std::unexpected{bytes.error()}; } if (Util::sha256_hex(*bytes) != sha256) { return std::unexpected{make_error( Void::System::SystemErrorCode::invalid_argument, std::format("StateStore: refusing to upload corrupted CAS blob '{}'", sha256))}; } return remote_->put_blob(sha256, *bytes); } Void::Result::Result StateStore::ensure_remote_blob(std::string_view sha256) { if (!is_valid_sha256_hex(sha256)) { return false; } auto local = verify_blob(sha256); if (!local) { return std::unexpected{local.error()}; } if (*local) { return true; } if (!remote_) { return false; } auto fetched = remote_->get_blob(sha256); if (!fetched) { return std::unexpected{fetched.error()}; } if (!fetched->has_value()) { return false; } const std::string &bytes = **fetched; if (Util::sha256_hex(bytes) != sha256) { return false; } const auto final_path = cas_blob_path(sha256); std::error_code ec; std::filesystem::create_directories(final_path.parent_path(), ec); const auto stage_path = staging_dir_ / std::format("remote_{}_{}.stage", sha256, g_lease_seq.fetch_add(1, std::memory_order_relaxed)); auto wrote = Platform::atomic_write_file(stage_path, bytes, true, 0644); if (!wrote) { return std::unexpected{wrote.error()}; } (void)::chmod(stage_path.c_str(), 0444); std::filesystem::rename(stage_path, final_path, ec); if (ec) { std::filesystem::remove(stage_path, ec); if (!std::filesystem::exists(final_path)) { return std::unexpected{make_error( Void::System::SystemErrorCode::io_error, std::format("StateStore: failed publishing remote CAS blob '{}'", sha256))}; } } (void)Platform::fsync_directory(final_path.parent_path()); return true; } Void::Result::Result, Void::Result::Error> StateStore::lookup_action(std::string_view action_key) const { std::optional found; { 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 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 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(db->generations.size() - 512)); } return save_db_locked(*db); } Void::Result::Result, Void::Result::Error> StateStore::list_generations(std::optional 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 filtered; for (const auto &g : db->generations) { if (g.profile_name == *profile_name) { filtered.push_back(g); } } return filtered; } Void::Result::Result StateStore::acquire_lease(std::string_view profile_name, const std::set &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(::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 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(&parsed->value)) { const auto pid = get_i64(*obj, "pid").value_or(0); if (!pid_is_alive(static_cast(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 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 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(&parsed->value)) { const auto pid = get_i64(*obj, "pid").value_or(0); if (!pid_is_alive(static_cast(pid))) { continue; } if (const auto *blobs = find_key(*obj, "blobs")) { if (const auto *arr = std::get_if(&blobs->value)) { for (const auto &bv : *arr) { if (const auto *s = std::get_if(&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