perf(config): memoize descriptor hashes by stat fingerprint; generate plugin tests
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 5s
VoidBuildSystem CI / fuzz-clang (push) Failing after 4s
VoidBuildSystem CI / sanitizers-gcc16 (push) Failing after 4s
VoidBuildSystem CI / signing-openssl-gcc16 (push) Failing after 10s
VoidBuildSystem CI / wine-windows-gcc16 (push) Failing after 58s

This commit is contained in:
faumaray committed 2026-12-05 12:33:56 +03:00
1 parent 09fd3cce39
commit e135ae3023
6 files changed
+306 -35

No files matched your search

+215 -21
View File
@@ -8,6 +8,7 @@
#include <Void/Data/StrictJson.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Types.hpp>
#include <Void/Time/Stopwatch.hpp>
#include <algorithm>
#include <atomic>
@@ -32,6 +33,31 @@ bool is_cpp_file(const std::filesystem::path &p) {
return ext == ".cpp" || ext == ".cc" || ext == ".cxx";
}
// Cheap identity of a header file: content hashing is only needed when this changes.
struct HeaderFingerprint {
std::int64_t size{0};
std::int64_t mtime{0};
bool operator==(const HeaderFingerprint &) const = default;
};
std::optional<HeaderFingerprint> stat_fingerprint(const std::filesystem::path &path) {
std::error_code ec;
if (!std::filesystem::is_regular_file(path, ec)) {
return std::nullopt;
}
const auto size = std::filesystem::file_size(path, ec);
if (ec) {
return std::nullopt;
}
const auto mtime = std::filesystem::last_write_time(path, ec);
if (ec) {
return std::nullopt;
}
return HeaderFingerprint{static_cast<std::int64_t>(size),
static_cast<std::int64_t>(mtime.time_since_epoch().count())};
}
std::string generate_driver_source(bool has_profiles_file, bool has_build_file,
bool has_workspace_file) {
std::string code = R"cpp(#include <Void/Build.hpp>
@@ -267,6 +293,93 @@ std::vector<std::string> get_str_array(const JsonVal::Object &obj, const std::st
return out;
}
// Persisted stat-fingerprint -> content-hash memo for descriptor identity inputs. Large SDK
// artifacts are hashed once and then trusted until their size or mtime changes.
class FileHashMemo {
public:
explicit FileHashMemo(std::filesystem::path cache_file) : cache_file_{std::move(cache_file)} {
auto text = Void::FileSystem::read_file(cache_file_);
if (!text) {
return;
}
auto parsed = Void::Json::Strict::parse(*text);
if (!parsed) {
return;
}
const auto *root = std::get_if<JsonVal::Object>(&parsed->value);
if (root == nullptr) {
return;
}
const auto *files_v = find_key(*root, "files");
const auto *files = files_v ? std::get_if<JsonVal::Object>(&files_v->value) : nullptr;
if (files == nullptr) {
return;
}
for (const auto &[path, value] : *files) {
const auto *entry = std::get_if<JsonVal::Object>(&value.value);
if (entry == nullptr) {
continue;
}
auto sha = get_str(*entry, "sha256");
auto size = get_i64(*entry, "size");
auto mtime = get_i64(*entry, "mtime");
if (sha && size && mtime) {
entries_[path] = Entry{std::move(*sha), HeaderFingerprint{*size, *mtime}};
}
}
}
[[nodiscard]] std::optional<std::string> lookup(const std::filesystem::path &path,
const HeaderFingerprint &fingerprint) const {
const auto it = entries_.find(path.string());
if (it != entries_.end() && it->second.fingerprint == fingerprint) {
return it->second.sha256;
}
return std::nullopt;
}
void store(const std::filesystem::path &path, const HeaderFingerprint &fingerprint,
std::string sha256) {
const auto key = path.string();
const auto it = entries_.find(key);
if (it != entries_.end() && it->second.fingerprint == fingerprint &&
it->second.sha256 == sha256) {
return;
}
entries_[key] = Entry{std::move(sha256), fingerprint};
dirty_ = true;
}
void flush() {
if (!dirty_) {
return;
}
std::string json = "{\"files\":{";
bool first = true;
for (const auto &[path, entry] : entries_) {
if (!first) {
json += ',';
}
first = false;
json += Util::json_quote(path) + ":{\"sha256\":" + Util::json_quote(entry.sha256) +
",\"size\":" + std::to_string(entry.fingerprint.size) +
",\"mtime\":" + std::to_string(entry.fingerprint.mtime) + '}';
}
json += "}}\n";
(void)Platform::atomic_write_file(cache_file_, json, false);
dirty_ = false;
}
private:
struct Entry {
std::string sha256;
HeaderFingerprint fingerprint;
};
std::filesystem::path cache_file_;
std::map<std::string, Entry, std::less<>> entries_;
bool dirty_{false};
};
} // namespace
Void::Result::Result<std::vector<std::filesystem::path>, Void::Result::Error>
@@ -340,10 +453,13 @@ discover_config_sources(const std::filesystem::path &project_root,
Void::Result::Result<CompiledDescriptor, Void::Result::Error>
compile_descriptor(const FrontendOptions &options) {
const auto phase_sw = Void::Time::Stopwatch::started();
auto sources_res = discover_config_sources(options.project_root, options.extra_build_sources);
if (!sources_res) {
return std::unexpected{sources_res.error()};
}
Void::Log::debug("Config", "descriptor sources discovered in {:.1f} ms ({} source(s))",
phase_sw.elapsed_ms(), sources_res->size());
std::error_code ec;
const auto canonical_root = std::filesystem::weakly_canonical(options.project_root, ec);
@@ -374,9 +490,30 @@ compile_descriptor(const FrontendOptions &options) {
host_cxx = *resolved;
}
auto host_hash = Util::sha256_file_hex(host_cxx);
// Memoized hashing: identity inputs are re-hashed only when their stat fingerprint changes.
FileHashMemo hash_memo{config_dir / "identity_cache.json"};
const auto memoized_hash =
[&](const std::filesystem::path &path) -> std::optional<std::string> {
const auto fingerprint = stat_fingerprint(path);
if (fingerprint) {
if (auto cached = hash_memo.lookup(path, *fingerprint)) {
return cached;
}
}
auto hash = Util::sha256_file_hex(path);
if (!hash) {
return std::nullopt;
}
if (fingerprint) {
hash_memo.store(path, *fingerprint, *hash);
}
return *hash;
};
auto host_hash = memoized_hash(host_cxx);
if (!host_hash) {
return std::unexpected{host_hash.error()};
return std::unexpected{
make_error(std::format("cannot hash host compiler '{}'", host_cxx.string()))};
}
const bool has_profiles =
@@ -398,33 +535,59 @@ compile_descriptor(const FrontendOptions &options) {
id_hasher.update_length_prefixed(*host_hash);
id_hasher.update_length_prefixed(driver_src);
if (!options.sdk_include_dir.empty()) {
if (auto hdr_h = Util::sha256_file_hex(options.sdk_include_dir / "Void" / "Build.hpp");
hdr_h) {
if (auto hdr_h = memoized_hash(options.sdk_include_dir / "Void" / "Build.hpp"); hdr_h) {
id_hasher.update_length_prefixed(*hdr_h);
}
}
if (!options.sdk_library_path.empty() &&
std::filesystem::exists(options.sdk_library_path, ec)) {
if (auto lib_h = Util::sha256_file_hex(options.sdk_library_path); lib_h) {
if (auto lib_h = memoized_hash(options.sdk_library_path); lib_h) {
id_hasher.update_length_prefixed(*lib_h);
}
}
for (const auto &src : *sources_res) {
auto h = Util::sha256_file_hex(src);
auto h = memoized_hash(src);
if (!h) {
return std::unexpected{h.error()};
return std::unexpected{
make_error(std::format("cannot hash configuration source '{}'", src.string()))};
}
id_hasher.update_length_prefixed(src.string());
id_hasher.update_length_prefixed(*h);
}
const std::string seed_id = id_hasher.finalize_hex();
hash_memo.flush();
Void::Log::debug("Config", "descriptor identity hashed in {:.1f} ms", phase_sw.elapsed_ms());
const auto exe_path = config_dir / ("descriptor_" + seed_id.substr(0, 16));
const auto meta_path = config_dir / ("descriptor_" + seed_id.substr(0, 16) + ".headers.json");
// Check if cached descriptor executable exists AND all previously discovered headers match!
// Header entries carry a stat fingerprint (size + mtime) beside the SHA-256: when the
// fingerprint is unchanged the content hash is trusted and no file is read. Legacy entries
// (plain hash strings) are still accepted and upgraded in place.
struct HeaderMeta {
std::string sha256;
HeaderFingerprint fingerprint;
};
bool up_to_date = false;
bool metadata_stale = false;
std::vector<std::filesystem::path> cached_headers;
std::map<std::string, HeaderMeta, std::less<>> verified_headers;
const auto write_meta = [&](const std::map<std::string, HeaderMeta, std::less<>> &headers) {
std::string meta_json = "{\"seed_id\":" + Util::json_quote(seed_id) + ",\"headers\":{";
bool first = true;
for (const auto &[hpath, meta] : headers) {
if (!first) {
meta_json += ',';
}
first = false;
meta_json += Util::json_quote(hpath) + ":{\"sha256\":" + Util::json_quote(meta.sha256) +
",\"size\":" + std::to_string(meta.fingerprint.size) +
",\"mtime\":" + std::to_string(meta.fingerprint.mtime) + '}';
}
meta_json += "}}\n";
(void)Platform::atomic_write_file(meta_path, meta_json, false);
};
if (std::filesystem::is_regular_file(exe_path, ec) &&
std::filesystem::is_regular_file(meta_path, ec)) {
if (auto meta_text = Void::FileSystem::read_file(meta_path); meta_text) {
@@ -435,13 +598,44 @@ compile_descriptor(const FrontendOptions &options) {
if (const auto *hv = find_key(*obj, "headers")) {
if (const auto *hobj = std::get_if<JsonVal::Object>(&hv->value)) {
for (const auto &[hpath, hval] : *hobj) {
const auto *expected = std::get_if<std::string>(&hval.value);
auto actual =
Util::sha256_file_hex(std::filesystem::path{hpath});
if (!expected || !actual || *actual != *expected) {
const std::filesystem::path header{hpath};
const auto fingerprint = stat_fingerprint(header);
if (!fingerprint) {
headers_ok = false;
break;
}
std::string expected_sha;
std::optional<HeaderFingerprint> expected_fp;
if (const auto *sha = std::get_if<std::string>(&hval.value)) {
expected_sha = *sha; // legacy entry
metadata_stale = true;
} else if (const auto *entry =
std::get_if<JsonVal::Object>(&hval.value)) {
expected_sha = get_str(*entry, "sha256").value_or("");
if (const auto size = get_i64(*entry, "size");
size && get_i64(*entry, "mtime")) {
expected_fp =
HeaderFingerprint{*size, *get_i64(*entry, "mtime")};
}
}
std::string actual_sha = expected_sha;
if (expected_fp && *expected_fp == *fingerprint &&
!expected_sha.empty()) {
// Unchanged stat fingerprint: trust the stored hash.
} else {
auto hashed = Util::sha256_file_hex(header);
if (!hashed || (expected_sha.empty() && !expected_fp)) {
headers_ok = false;
break;
}
if (!expected_sha.empty() && *hashed != expected_sha) {
headers_ok = false;
break;
}
actual_sha = std::move(*hashed);
metadata_stale = true;
}
verified_headers[hpath] = HeaderMeta{actual_sha, *fingerprint};
cached_headers.emplace_back(hpath);
}
}
@@ -452,6 +646,11 @@ compile_descriptor(const FrontendOptions &options) {
}
}
}
if (up_to_date && metadata_stale) {
write_meta(verified_headers);
}
Void::Log::debug("Config", "descriptor check: seed identity + cache in {:.1f} ms",
phase_sw.elapsed_ms());
if (up_to_date) {
CompiledDescriptor desc;
@@ -563,20 +762,15 @@ compile_descriptor(const FrontendOptions &options) {
return std::unexpected{make_error("failed publishing compiled descriptor executable")};
}
// Persist discovered header hashes atomically.
std::string meta_json = "{\"seed_id\":" + Util::json_quote(seed_id) + ",\"headers\":{";
bool first = true;
// Persist discovered header hashes (with stat fingerprints) atomically.
std::map<std::string, HeaderMeta, std::less<>> persisted_headers;
std::vector<std::filesystem::path> headers_list;
for (const auto &[hpath, hsha] : header_hashes) {
if (!first) {
meta_json += ',';
}
first = false;
meta_json += Util::json_quote(hpath) + ':' + Util::json_quote(hsha);
const auto fingerprint = stat_fingerprint(hpath);
persisted_headers[hpath] = HeaderMeta{hsha, fingerprint.value_or(HeaderFingerprint{})};
headers_list.emplace_back(hpath);
}
meta_json += "}}\n";
(void)Platform::atomic_write_file(meta_path, meta_json, false);
write_meta(persisted_headers);
CompiledDescriptor desc;
desc.executable_path = exe_path;
+64 -13
View File
@@ -1212,6 +1212,7 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
" \"categories\": [\"Other\"],\n"
" \"activationEvents\": [],\n"
" \"main\": \"./extension.js\",\n"
" \"scripts\": {\"test\": \"node test/extension.test.js\"},\n"
" \"contributes\": {\n \"commands\": " +
json_array(commands,
[](const PluginCommand &command) {
@@ -1232,7 +1233,8 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
" const terminal = vscode.window.createTerminal({ name });\n"
" terminal.show(true);\n"
" const full = [...args, ...projectArgs()];\n"
" terminal.sendText([vbs, ...full].map((a) => (a.includes(' ') ? `'${a}'` : a)).join(' '));\n"
" terminal.sendText([vbs, ...full].map((a) => (a.includes(' ') ? `'${a}'` : a)).join(' "
"'));\n"
"}\n\n"
"const commands = [\n";
for (const auto &command : commands) {
@@ -1249,6 +1251,51 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
"function deactivate() {}\n\n"
"module.exports = { activate, deactivate };\n";
// Executes the extension against a mocked VS Code API (`npm test`).
const std::string vscode_test_js =
std::string{} +
R"js(// Generated by `vbs ide plugin`: runs extension.js against a mocked VS Code API.
const Module = require('module');
const registered = new Map();
const terminals = [];
const workspace = '/tmp/vbs-workspace';
const vscodeMock = {
window: {
createTerminal: ({ name }) => ({
name,
show() {},
sendText(text) { terminals.push({ name, text }); },
}),
},
commands: {
registerCommand: (id, fn) => { registered.set(id, fn); return { dispose() {} }; },
},
workspace: { workspaceFolders: [{ uri: { fsPath: workspace } }] },
};
const originalLoad = Module._load;
Module._load = function (request) {
if (request === 'vscode') return vscodeMock;
return originalLoad.apply(this, arguments);
};
const extension = require('../extension.js');
extension.activate({ subscriptions: [] });
for (const [, fn] of registered) fn();
)js" +
"const expectedCommands = " + std::to_string(commands.size()) + ";\n" +
R"js(if (registered.size !== expectedCommands)
throw new Error('expected ' + expectedCommands + ' commands, got ' + registered.size);
if (terminals.length !== registered.size) throw new Error('every command must open a terminal');
const build = terminals.find((t) => t.name === 'VBS: Build');
if (!build) throw new Error('build command missing');
if (!build.text.includes('build')) throw new Error('build args missing: ' + build.text);
if (!build.text.includes('--project ' + workspace))
throw new Error('workspace project not injected: ' + build.text);
const install = terminals.find((t) => t.name === 'VBS: Install');
if (!install || !install.text.includes('--prefix')) throw new Error('install prefix missing');
extension.deactivate();
console.log('extension tests passed: ' + terminals.length + ' commands');
)js";
const std::string readme = std::format(
"# VoidBuildSystem editor extension\n\n"
"Generated by `vbs ide plugin` for the project at `{}`.\n\n"
@@ -1295,8 +1342,8 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
for (const auto &[name, content] :
std::vector<std::pair<std::string, std::string>>{{"extension.toml", zed_manifest},
{"tasks.json", zed_tasks},
{"README.md", zed_readme}}) {
{"tasks.json", zed_tasks},
{"README.md", zed_readme}}) {
if (auto written = write_asset(output / name, content); !written) {
return std::unexpected{written.error()};
}
@@ -1309,7 +1356,8 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
" <id>com.faumaray.vbs</id>\n"
" <name>VoidBuildSystem</name>\n"
" <vendor>Void</vendor>\n"
" <description>Build, test, install and package with VoidBuildSystem (VBS).</description>\n"
" <description>Build, test, install and package with VoidBuildSystem "
"(VBS).</description>\n"
" <depends>com.intellij.modules.platform</depends>\n"
" <depends>com.intellij.modules.cidr.lang</depends>\n"
" <actions>\n"
@@ -1319,7 +1367,8 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
" </action>\n"
" <action id=\"Vbs.Install\" class=\"com.faumaray.vbs.InstallAction\"\n"
" text=\"VBS: Install\" description=\"Stage an install prefix\">\n"
" <add-to-group group-id=\"ToolsMenu\" anchor=\"after\" relative-to-action=\"Vbs.Build\"/>\n"
" <add-to-group group-id=\"ToolsMenu\" anchor=\"after\" "
"relative-to-action=\"Vbs.Build\"/>\n"
" </action>\n"
" </actions>\n"
"</idea-plugin>\n";
@@ -1363,7 +1412,8 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
"class InstallAction : AnAction(\"VBS: Install\") {\n"
" override fun actionPerformed(event: AnActionEvent) {\n"
" event.project?.let {\n"
" runVbs(it, \"install\", listOf(\"install\", \"--prefix\", \"build/install\"))\n"
" runVbs(it, \"install\", listOf(\"install\", \"--prefix\", "
"\"build/install\"))\n"
" }\n"
" }\n"
"}\n";
@@ -1371,11 +1421,11 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
"# VbsCLion\n\nCLion (JetBrains) plugin assets for VoidBuildSystem, generated by "
"`vbs ide plugin --editor clion`.\n\nCLion can also read the CMake File API document "
"emitted by `vbs ide generate`, so this plugin is complementary: it adds Tools-menu "
"actions for `vbs build` and `vbs install`.\n\n```sh\n./gradlew buildPlugin\n```\n\nSet "
"actions for `vbs build` and `vbs install`.\n\n```sh\n./gradlew "
"buildPlugin\n```\n\nSet "
"`VBS_BIN` if `vbs` is not on `PATH`.\n";
for (const auto &[name, content] :
std::vector<std::pair<std::string, std::string>>{
for (const auto &[name, content] : std::vector<std::pair<std::string, std::string>>{
{"src/main/resources/META-INF/plugin.xml", plugin_xml},
{"build.gradle.kts", gradle},
{"src/main/kotlin/com/faumaray/vbs/VbsActions.kt", action_kt},
@@ -1392,10 +1442,11 @@ export_ide_plugin_assets(const IdePluginOptions &options) {
"editor plugin assets are generated for vscode, zed and clion only")};
}
for (const auto &[name, content] :
std::vector<std::pair<std::string, std::string>>{{"package.json", package_json},
{"extension.js", extension_js},
{"README.md", readme}}) {
for (const auto &[name, content] : std::vector<std::pair<std::string, std::string>>{
{"package.json", package_json},
{"extension.js", extension_js},
{"test/extension.test.js", vscode_test_js},
{"README.md", readme}}) {
if (auto written = write_asset(output / name, content); !written) {
return std::unexpected{written.error()};
}