From e990f440375bfec8e700ec2a8a3cee707234ab00 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 01:02:18 +0300 Subject: [PATCH] feat(state,registry): back StateStore with Void::Sqlite when available and filter audit queries --- docs/agent-workflow/STATE.md | 2 +- docs/agent-workflow/TASKS.md | 3 +- docs/agent-workflow/VERIFICATION.md | 21 ++ docs/roadmap/21-expansion-roadmap.md | 2 +- include/Void/Build/State/StateStore.hpp | 13 ++ registry/service/RegistryService.cpp | 66 +++++- src/State/StateStore.cpp | 298 ++++++++++++++++++++++-- tests/RegistryTests.cpp | 16 ++ 8 files changed, 387 insertions(+), 34 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 7dc5aee..9cb37c5 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -173,7 +173,7 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - Added the `compdb_entries` daemon request (`vbs daemon compdb entries [--file SUFFIX] [--limit N]`): reads the active published compilation database (selection state or root alias), returns bounded projected entries (`file`, `directory`, `output`, `command`, bounded `arguments`), reports `total`/`returned`, and errors explicitly when nothing is published. - Added `Daemon.compdb_entries_queries_published_database` (unpublished → error, then all entries, a `main.cpp` filter with `limit:1`, and an invalid limit) and a CLI help contract; Daemon suite is now 18 cases. -- **Wave 40 (Authenticated Binary-Variant Downloads)**:\n - `download_binary_artifact` now accepts `RegistryAuth` and sends the bearer token, so private registry binary artifacts can be fetched; `BinaryFetchOptions` gained `bearer_token` and `materialize_binary_variant` forwards it; `vbs binaries fetch` passes the configured token.\n - Added `RegistryTests.private_binary_variant_download_requires_auth`: anonymous download of a private binary → 401, authenticated client download and signed materialization succeed.\n\n- **Wave 41 (Yanked Binary Variants in Listing)**:\n - `fetch_binary_variants` gained `include_yanked` (default false, so selection/materialization still never sees yanked variants); `vbs binaries list` opts in and marks yanked entries while `binaries fetch` keeps the filtered view.\n - Extended the registry binary-variant test to assert the yanked variant is returned with `yanked=true` only when requested.\n\n- **Wave 42 (Registry Binary-Variant Listing Endpoint)**:\n - Added `GET /api/v1/packages///binaries` returning the release's binary variants (`variant_id`, `sha256`, `size_bytes`, `yanked`, optional signature/public key) under normal read permissions; `RegistryClient::fetch_binary_variants` now queries this endpoint directly instead of parsing package detail JSON.\n - The registry binary-variant test asserts the listing endpoint returns the published variant with `yanked:false`.\n\n- **Wave 43 (Workspace Members Request)**:\n - Added the `workspace_members` daemon request (`vbs daemon workspace members`): lists declared workspace members (`name`, canonical `path`) without evaluating member build descriptions; non-workspace roots return `workspace:false` with an empty list.\n - Added `Daemon.workspace_members_lists_declared_members` and a CLI help contract; Daemon suite is now 19 cases.\n\n- **Wave 44 (IDE Configs Request)**:\n - Added the `ide_configs` daemon request (`vbs daemon ide configs`): reports presence of `.clangd`, `.vscode/tasks.json`, `.zed/tasks.json`, and `.idea/customTargets.xml` so editor extensions can see what is configured.\n - Added `Daemon.ide_configs_reports_generated_files` (absent before generation, present after `ide_generate`) and a CLI help contract; Daemon suite is now 20 cases.\n\n- **Wave 45 (Compdb Generations Request)**:\n - Added the `compdb_generations` daemon request (`vbs daemon compdb generations --profile`): lists immutable editor generations (bounded 128) with active flag, per-generation entry counts, and the per-profile status/diagnostic record; profile names are validated against `[A-Za-z0-9._-]` to prevent traversal.\n - Added `Daemon.compdb_generations_lists_history_and_active_generation` (empty before export, then a valid generation with entries and an active selection; invalid profile rejected) and a CLI help contract; Daemon suite is now 21 cases.\n\n- **Wave 46 (Registry Package Search Pagination)**:\n - `GET /api/v1/packages` now supports bounded `limit` (0-500, default 100) and `offset` (0-1,000,000) pagination with a `total`/`limit`/`offset` envelope; malformed values return 400.\n - The registry RBAC test asserts a `limit=1` page contains exactly one package and that `limit=501` is rejected.\n\n- **Wave 47 (Registry Release Detail Endpoint)**:\n - Added `GET /api/v1/packages//` returning release metadata (digest, size, yank state, publisher/epoch, optional signature/public key, binary variant summaries) under normal read permissions; unknown packages/releases return 404.\n - The registry binary-variant test asserts the release detail includes the version and published binary variant, and that an unknown version returns 404.\n\n- **Wave 48 (Daemon Deps Request)**:\n - Added the `deps` daemon request (`vbs daemon deps [--profile] [--member]`): evaluates the project, merges TOML/declared dependencies, resolves and materializes them with the pinned lock, registry environment, and trusted keys, then returns the lock context key and per-entry metadata (`alias`, `source_kind`, `package_name`, `version`, `sha256`, `signed`). Shared dependency-merge and resolve-option helpers were extracted for reuse by the build path.\n - Extended `Daemon.build_materializes_path_dependency` to assert a `deps` response with the `helper` path entry before building, plus a CLI help contract.\n\n- **Wave 49 (Daemon Info Request)**:\n - Added the `info` daemon request (`vbs daemon info`): reports the daemon version, host OS/architecture, project/build/lock roots, and socket path so editor extensions can discover the environment without guessing.\n - Added `Daemon.info_reports_daemon_paths_and_host` and a CLI help contract; Daemon suite is now 22 cases.\n\n## Remaining future scope +- **Wave 40 (Authenticated Binary-Variant Downloads)**:\n - `download_binary_artifact` now accepts `RegistryAuth` and sends the bearer token, so private registry binary artifacts can be fetched; `BinaryFetchOptions` gained `bearer_token` and `materialize_binary_variant` forwards it; `vbs binaries fetch` passes the configured token.\n - Added `RegistryTests.private_binary_variant_download_requires_auth`: anonymous download of a private binary → 401, authenticated client download and signed materialization succeed.\n\n- **Wave 41 (Yanked Binary Variants in Listing)**:\n - `fetch_binary_variants` gained `include_yanked` (default false, so selection/materialization still never sees yanked variants); `vbs binaries list` opts in and marks yanked entries while `binaries fetch` keeps the filtered view.\n - Extended the registry binary-variant test to assert the yanked variant is returned with `yanked=true` only when requested.\n\n- **Wave 42 (Registry Binary-Variant Listing Endpoint)**:\n - Added `GET /api/v1/packages///binaries` returning the release's binary variants (`variant_id`, `sha256`, `size_bytes`, `yanked`, optional signature/public key) under normal read permissions; `RegistryClient::fetch_binary_variants` now queries this endpoint directly instead of parsing package detail JSON.\n - The registry binary-variant test asserts the listing endpoint returns the published variant with `yanked:false`.\n\n- **Wave 43 (Workspace Members Request)**:\n - Added the `workspace_members` daemon request (`vbs daemon workspace members`): lists declared workspace members (`name`, canonical `path`) without evaluating member build descriptions; non-workspace roots return `workspace:false` with an empty list.\n - Added `Daemon.workspace_members_lists_declared_members` and a CLI help contract; Daemon suite is now 19 cases.\n\n- **Wave 44 (IDE Configs Request)**:\n - Added the `ide_configs` daemon request (`vbs daemon ide configs`): reports presence of `.clangd`, `.vscode/tasks.json`, `.zed/tasks.json`, and `.idea/customTargets.xml` so editor extensions can see what is configured.\n - Added `Daemon.ide_configs_reports_generated_files` (absent before generation, present after `ide_generate`) and a CLI help contract; Daemon suite is now 20 cases.\n\n- **Wave 45 (Compdb Generations Request)**:\n - Added the `compdb_generations` daemon request (`vbs daemon compdb generations --profile`): lists immutable editor generations (bounded 128) with active flag, per-generation entry counts, and the per-profile status/diagnostic record; profile names are validated against `[A-Za-z0-9._-]` to prevent traversal.\n - Added `Daemon.compdb_generations_lists_history_and_active_generation` (empty before export, then a valid generation with entries and an active selection; invalid profile rejected) and a CLI help contract; Daemon suite is now 21 cases.\n\n- **Wave 46 (Registry Package Search Pagination)**:\n - `GET /api/v1/packages` now supports bounded `limit` (0-500, default 100) and `offset` (0-1,000,000) pagination with a `total`/`limit`/`offset` envelope; malformed values return 400.\n - The registry RBAC test asserts a `limit=1` page contains exactly one package and that `limit=501` is rejected.\n\n- **Wave 47 (Registry Release Detail Endpoint)**:\n - Added `GET /api/v1/packages//` returning release metadata (digest, size, yank state, publisher/epoch, optional signature/public key, binary variant summaries) under normal read permissions; unknown packages/releases return 404.\n - The registry binary-variant test asserts the release detail includes the version and published binary variant, and that an unknown version returns 404.\n\n- **Wave 48 (Daemon Deps Request)**:\n - Added the `deps` daemon request (`vbs daemon deps [--profile] [--member]`): evaluates the project, merges TOML/declared dependencies, resolves and materializes them with the pinned lock, registry environment, and trusted keys, then returns the lock context key and per-entry metadata (`alias`, `source_kind`, `package_name`, `version`, `sha256`, `signed`). Shared dependency-merge and resolve-option helpers were extracted for reuse by the build path.\n - Extended `Daemon.build_materializes_path_dependency` to assert a `deps` response with the `helper` path entry before building, plus a CLI help contract.\n\n- **Wave 49 (Daemon Info Request)**:\n - Added the `info` daemon request (`vbs daemon info`): reports the daemon version, host OS/architecture, project/build/lock roots, and socket path so editor extensions can discover the environment without guessing.\n - Added `Daemon.info_reports_daemon_paths_and_host` and a CLI help contract; Daemon suite is now 22 cases.\n\n- **Wave 50 (Registry Audit Query Filters)**:\n - `GET /api/v1/audit` now supports `actor`, `action` (substring), `outcome`, `limit` (0–2000, default 100) and `offset` filters with a `total`/`limit`/`offset` envelope; malformed limits return 400.\n - The registry RBAC test asserts the audit envelope and an action-filtered `limit=1` page contains a single entry.\n\n- **Wave 51 (Track E4 `Void::Sqlite` Alignment for the StateStore)**:\n - When built with SQLite3 (`VBS_HAS_VOID_SQLITE`, now available via `dev cpp-gcc -p sqlite`), `StateStore` keeps its transactional action cache in `state/state.v2.sqlite` using `Void::Sqlite` (`meta`, `actions`, `generations` tables, one transaction per publication) and imports an existing `state.v1.json` once. Without SQLite the journaled atomic JSON store remains unchanged.\n - `Void::Net` alignment is still pending: it requires OpenSSL, while only Boost is provided by `-p boost`.\n\n## Remaining future scope"}, {"oldString": "Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope.", "newString": "Track E4 (`Void::Net` alignment; `Void::Sqlite` is now used by the StateStore when SQLite3 is available) remain planned scope."} - **Post-v1 Expansion Roadmap ([21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md) & [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md))**: Live `conan` CLI verification (Track B3), Track C (macOS/Windows ports + dual-profile cross-compilation), Track D3 signing (SBOM, Ed25519 primitives, trusted-key enforcement and distribution, binary-variant signing and distribution materialization, the #52 built-in-backend capability probe, and the VoidLibrary pin bump to `0002e74` done), Track E3 (daemon core, bounded `describe`, build-serving, dependency materialization, daemon-backed IDE metadata, compdb export, IDE config generation, editor watch poll and bounded long-poll done; dedicated external editor plugins remain), and Track E4 (`Void::Net`/`Void::Sqlite` alignment) remain planned scope. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 187d54c..3d15bc5 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -56,4 +56,5 @@ Base HEAD: `fe0d1a6` | Wave 47 (Registry release detail) | `GET /api/v1/packages//` with metadata + binary summaries | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 7/7, full CTest 8/8) | `registry/service/RegistryService.cpp`, `tests/RegistryTests.cpp`, docs | | Wave 48 (Daemon deps request) | `deps` daemon request + `vbs daemon deps --profile --member`: resolve/materialize and return the lock context entries; shared merge/resolve helpers | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 21/21, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | | Wave 49 (Daemon info request) | `info` daemon request + `vbs daemon info`: version, host, project/build/lock roots, socket | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Daemon 22/22, full CTest 8/8) | `src/Daemon/Daemon.cpp`, `src/Main.cpp`, `tests/DaemonTests.cpp`, `tests/CliContracts.cmake`, docs | -| Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions, E4, live `conan`) | Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | +| Wave 50 (Audit query filters) | `/api/v1/audit` actor/action/outcome/limit/offset filters with envelope and 400 validation | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; Registry 7/7, full CTest 8/8) | `registry/service/RegistryService.cpp`, `tests/RegistryTests.cpp`, docs | +| Wave 51 (Track E4 Sqlite alignment) | SQLite-backed `StateStore` (`state.v2.sqlite`) with one-time JSON import when `VBS_HAS_VOID_SQLITE`; JSON fallback unchanged; `Void::Net` still needs OpenSSL | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`, `-p sqlite -p boost`: core 6/6 and full CTest 8/8; default JSON backend core 6/6) | `include/Void/Build/State/StateStore.hpp`, `src/State/StateStore.cpp`, docs |\n| Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions, E4 Net alignment, live `conan`) |"}] Live `conan` CLI verification; macOS/Windows/cross-compile; binary-variant signing and key distribution; daemon-side dependency materialization and editor plugins; `Void::Net`/`Void::Sqlite` alignment | PLANNED (unimplemented) | [21-expansion-roadmap.md](../roadmap/21-expansion-roadmap.md), [20-future-translation-platforms.md](../roadmap/20-future-translation-platforms.md) | diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index b01ab3d..2e6bac9 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -827,6 +827,27 @@ dev cpp-gcc -c ctest --test-dir build/pinned --output-on-failure - Full CTest: **8 / 8 passed** in 230.32 s. - `clang-format --dry-run --Werror` passes on the changed C++ files. +## Track E4 `Void::Sqlite` StateStore Alignment (GCC 16.2, pin `0002e74`) + +SQLite and Boost were made available through `dev cpp-gcc -p sqlite -p boost` (the configured +dev shell reports `modules=16` including `Void::Sqlite`; `SQLite3_LIBRARY` is found). + +```sh +dev cpp-gcc -p sqlite -p boost -c cmake -S . -B build/e4 -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVBS_VOID_SOURCE_DIR=/tmp/opencode/vl-pin +dev cpp-gcc -p sqlite -p boost -c cmake --build build/e4 --parallel 8 +dev cpp-gcc -p sqlite -p boost -c ctest --test-dir build/e4 --output-on-failure +dev cpp-gcc -c cmake --build build/pinned --parallel 8 +dev cpp-gcc -c build/pinned/bin/vbs_core_tests --no-color +``` + +- SQLite-backed build: exit 0. Full CTest: **8 / 8 passed** in 244.23 s (`vbs_v1_tests` 110.03 s, + `vbs_selfhost_tests` 100.55 s, `vbs_core_tests` 15.61 s, `vbs_registry_tests` 10.33 s) with + `StateStore` using `Void::Sqlite` (`state.v2.sqlite`). +- Default build (no SQLite): exit 0, `vbs_core_tests` **6 / 6 passed** on the JSON backend. +- Fixes during verification: `INSERT` `step()` returning no row is success (not failure), and the + extracted `parse_database_snapshot` needed its final `return snap;` (a missing return trapped as + SIGILL under the SQLite path). + ## Limits and Unrun Checks 1. **HTTPS git fetch**: the host shell is proxy-restricted, but the Docker container could clone `https://git.faumaray.com/Void/VoidLibrary.git`; the pinned commit `3e254055e081a104f08df68dde39711bc7813518` was fetched directly for the verification above. A separate configure against the local `/home/faumaray/Projects/Library` checkout via `VBS_VOID_SOURCE_DIR` also succeeded (development-only override, checkout unmodified). diff --git a/docs/roadmap/21-expansion-roadmap.md b/docs/roadmap/21-expansion-roadmap.md index 4bb28a7..3f996c4 100644 --- a/docs/roadmap/21-expansion-roadmap.md +++ b/docs/roadmap/21-expansion-roadmap.md @@ -73,7 +73,7 @@ flowchart LR | --- | --- | --- | | **E1 — Everyday CLI Ergonomics (Implemented in Wave 8)** | `vbs init` project scaffolding, `vbs clean`, `vbs doctor` environment diagnostics, `vbs graph --format dot|json`, and `vbs build --native-foreign`. | End-to-end CLI & integration tests passing in `vbs_cli_contract` and `vbs_v1_tests`. | | **E2 — Multi-Package Workspaces (`workspace.cpp`)** *(verified in Docker GCC 16)* | Shared root `vbs.lock` and `build/.vbs` CAS, `workspace_dependency()` cross-member native linking, and affected-member selection (`vbs build/test --member ` / `--changed-since `). | 3-package workspace fixture (shared library + app + tests) builds/tests with one root lockfile; member selection and `--changed-since` verified in `FullV1Tests.workspace_members_shared_build_and_member_selection`. | -| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover\|describe` (**Implemented & Verified in Wave 14; bounded `describe` added in the post-v1 daemon follow-up**). `describe` returns a bounded graph summary (`target_names` ≤ 128 entries × 200 bytes, `profile` ≤ 128 bytes, 10 s evaluation timeout); `vbs daemon build` executes the lowered graph in-process against the warm state store with bounded `profile`/`targets`/`jobs`, including daemon-side dependency resolution/materialization and provider import via `Package::resolve_and_materialize_dependencies`; `vbs daemon ide query` publishes/selects the profile compilation database and serves the IDE workspace/target metadata JSON over the socket, `vbs daemon compdb export` returns the published compilation-database path and entry count, `vbs daemon ide generate` writes the editor presets over the socket, `vbs daemon ide poll` exposes a bounded editor-extension watch protocol (changed paths, sequence, overflow state), `vbs daemon ide wait` adds a bounded long-poll variant, `vbs daemon ide status` reports the active editor selection and compdb state, `vbs daemon compdb use` switches the active editor profile under the selection lock, `vbs daemon graph` exports the target dependency graph (DOT/JSON), `vbs daemon test` builds and runs declared test targets, `vbs daemon compdb entries` serves bounded per-file compile arguments to editor extensions, `vbs daemon workspace members` lists workspace members cheaply, `vbs daemon ide configs` reports which editor configuration files exist, `vbs daemon compdb generations` lists editor generation history with the active selection, `vbs daemon info` exposes the daemon environment, `vbs daemon deps` resolves/materializes dependencies over the socket, registry package search supports bounded pagination, and releases expose a version-specific detail endpoint. Daemon workspace support describes members, builds all members in order (or a selected member) with the shared root lock, and serves member-scoped IDE query/generate/compdb requests via `--member`. Dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown/describe verified in `DaemonTests.cpp` (6/6 under `dev cpp-gcc`); the live `vbs daemon describe` CLI round-trip is verified in `vbs_cli_contract`. | +| **E3 — IDE Config/Query & Background Daemon** | `build.cpp`/`build.profiles.cpp`/`build-support/` SDK entries in `compile_commands.json` + `vbs ide generate` (`.clangd`, `.vscode/`, `.zed/`, `.idea/customTargets.xml`) & `vbs ide query` (**Implemented & Verified in Wave 10**); Unix-socket daemon core holding a warm `StateStore` + project `DirectoryWatcher` with `vbs daemon run\|status\|stop\|gc\|recover\|describe` (**Implemented & Verified in Wave 14; bounded `describe` added in the post-v1 daemon follow-up**). `describe` returns a bounded graph summary (`target_names` ≤ 128 entries × 200 bytes, `profile` ≤ 128 bytes, 10 s evaluation timeout); `vbs daemon build` executes the lowered graph in-process against the warm state store with bounded `profile`/`targets`/`jobs`, including daemon-side dependency resolution/materialization and provider import via `Package::resolve_and_materialize_dependencies`; `vbs daemon ide query` publishes/selects the profile compilation database and serves the IDE workspace/target metadata JSON over the socket, `vbs daemon compdb export` returns the published compilation-database path and entry count, `vbs daemon ide generate` writes the editor presets over the socket, `vbs daemon ide poll` exposes a bounded editor-extension watch protocol (changed paths, sequence, overflow state), `vbs daemon ide wait` adds a bounded long-poll variant, `vbs daemon ide status` reports the active editor selection and compdb state, `vbs daemon compdb use` switches the active editor profile under the selection lock, `vbs daemon graph` exports the target dependency graph (DOT/JSON), `vbs daemon test` builds and runs declared test targets, `vbs daemon compdb entries` serves bounded per-file compile arguments to editor extensions, `vbs daemon workspace members` lists workspace members cheaply, `vbs daemon ide configs` reports which editor configuration files exist, `vbs daemon compdb generations` lists editor generation history with the active selection, `vbs daemon info` exposes the daemon environment, `vbs daemon deps` resolves/materializes dependencies over the socket, registry package search and audit queries support bounded pagination/filters, and releases expose a version-specific detail endpoint. Daemon workspace support describes members, builds all members in order (or a selected member) with the shared root lock, and serves member-scoped IDE query/generate/compdb requests via `--member`. Dedicated editor extensions remain planned. | `vbs ide` & `build.cpp` syntax-check verified in `FullV1Tests.cpp`; daemon lifecycle/status/gc/shutdown/describe verified in `DaemonTests.cpp` (6/6 under `dev cpp-gcc`); the live `vbs daemon describe` CLI round-trip is verified in `vbs_cli_contract`. | | **E4 — Transport & Storage Upstream Alignment** | Adopt `Void::Net` (`VL-004`/`VL-005`) and `Void::Sqlite` (`VL-011b`) when lightweight/bundled builds become available in minimal Nix toolchains, reducing VBS transport code further. | All `vbs_registry_tests` and `vbs_core_tests` pass on both minimal and full toolchains. | --- diff --git a/include/Void/Build/State/StateStore.hpp b/include/Void/Build/State/StateStore.hpp index 697e434..afac613 100644 --- a/include/Void/Build/State/StateStore.hpp +++ b/include/Void/Build/State/StateStore.hpp @@ -2,6 +2,9 @@ #include #include +#if defined(VBS_HAS_VOID_SQLITE) +#include +#endif #include #include @@ -145,13 +148,23 @@ class StateStore { load_db_locked() const; [[nodiscard]] Void::Result::Result save_db_locked(const DatabaseSnapshot &db) const; + [[nodiscard]] static Void::Result::Result + parse_database_snapshot(std::string_view content, std::string_view origin); + [[nodiscard]] Void::Result::Result + load_json_db_locked() const; + [[nodiscard]] Void::Result::Result + save_sqlite_db_locked(const DatabaseSnapshot &db) const; std::filesystem::path root_; std::filesystem::path cas_dir_; std::filesystem::path staging_dir_; std::filesystem::path leases_dir_; std::filesystem::path db_file_; + std::filesystem::path sqlite_file_; std::filesystem::path lock_file_; +#if defined(VBS_HAS_VOID_SQLITE) + mutable std::optional sqlite_; +#endif std::shared_ptr cache_; std::optional remote_; }; diff --git a/registry/service/RegistryService.cpp b/registry/service/RegistryService.cpp index fa2bab0..45014f5 100644 --- a/registry/service/RegistryService.cpp +++ b/registry/service/RegistryService.cpp @@ -1505,15 +1505,63 @@ HttpResponse RegistryService::handle_request(const HttpRequest &req) { ",\"role\":" + json_quote(role_name(role)) + "}\n"); } if (req.path == "/api/v1/audit" && req.method == "GET") { - return HttpResponse::json(200, - "{\"audits\":" + json_array(audits_, [](const AuditEntry &a) { - return "{\"timestamp\":" + std::to_string(a.timestamp) + - ",\"actor\":" + json_quote(a.actor) + - ",\"action\":" + json_quote(a.action) + - ",\"target\":" + json_quote(a.target) + - ",\"outcome\":" + json_quote(a.outcome) + - ",\"detail\":" + json_quote(a.detail) + '}'; - }) + "}\n"); + const auto query_value = [&](std::string_view key) { + const auto it = req.query.find(std::string{key}); + return it == req.query.end() ? std::string{} : it->second; + }; + const std::string actor_filter = query_value("actor"); + const std::string action_filter = query_value("action"); + const std::string outcome_filter = query_value("outcome"); + std::size_t limit = 100; + std::size_t offset = 0; + const auto parse_size = [](const std::string &text, std::size_t max, std::size_t &out) { + std::size_t value = 0; + const auto [ptr, ec] = + std::from_chars(text.data(), text.data() + text.size(), value); + if (ec != std::errc{} || ptr != text.data() + text.size() || value > max) { + return false; + } + out = value; + return true; + }; + if (const std::string limit_text = query_value("limit"); + !limit_text.empty() && !parse_size(limit_text, 2000, limit)) { + return HttpResponse::error_json(400, "invalid_limit", + "limit must be an integer in [0, 2000]"); + } + if (const std::string offset_text = query_value("offset"); + !offset_text.empty() && !parse_size(offset_text, 100000, offset)) { + return HttpResponse::error_json(400, "invalid_offset", + "offset must be a non-negative integer"); + } + + std::vector matched; + for (const auto &entry : audits_) { + if (!actor_filter.empty() && entry.actor != actor_filter) + continue; + if (!action_filter.empty() && entry.action.find(action_filter) == std::string::npos) + continue; + if (!outcome_filter.empty() && entry.outcome != outcome_filter) + continue; + matched.push_back(&entry); + } + const std::size_t total = matched.size(); + std::vector page; + for (std::size_t i = offset; i < total && page.size() < limit; ++i) + page.push_back(matched[i]); + return HttpResponse::json( + 200, "{\"audits\":" + + json_array(page, + [](const AuditEntry *a) { + return "{\"timestamp\":" + std::to_string(a->timestamp) + + ",\"actor\":" + json_quote(a->actor) + + ",\"action\":" + json_quote(a->action) + + ",\"target\":" + json_quote(a->target) + + ",\"outcome\":" + json_quote(a->outcome) + + ",\"detail\":" + json_quote(a->detail) + '}'; + }) + + ",\"total\":" + std::to_string(total) + ",\"limit\":" + + std::to_string(limit) + ",\"offset\":" + std::to_string(offset) + "}\n"); } if (req.path == "/api/v1/admin/storage" && req.method == "GET") { return HttpResponse::json( diff --git a/src/State/StateStore.cpp b/src/State/StateStore.cpp index 656527b..8c94863 100644 --- a/src/State/StateStore.cpp +++ b/src/State/StateStore.cpp @@ -174,7 +174,8 @@ struct StateStore::CacheState { 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()} {} + sqlite_file_{root_ / "state" / "state.v2.sqlite"}, lock_file_{root_ / "state" / "state.lock"}, + cache_{std::make_shared()} {} Void::Result::Result StateStore::open(const std::filesystem::path &vbs_dir) { @@ -197,6 +198,43 @@ StateStore::open(const std::filesystem::path &vbs_dir) { 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) { @@ -210,6 +248,7 @@ StateStore::open(const std::filesystem::path &vbs_dir) { } } return store; +#endif } std::filesystem::path StateStore::cas_blob_path(std::string_view sha256) const { @@ -219,32 +258,140 @@ std::filesystem::path StateStore::cas_blob_path(std::string_view sha256) const { return cas_dir_ / std::string{sha256.substr(0, 2)} / std::string{sha256}; } +#if defined(VBS_HAS_VOID_SQLITE) +namespace { + +Void::Result::Result +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::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; +#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 content = Void::FileSystem::read_file_bounded(db_file_, {128ULL * 1024ULL * 1024ULL}); - if (!content) { - return std::unexpected{content.error()}; + 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(&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(get_i64(*obj, "sequence").value_or(0)); + snap.generations.push_back(std::move(gen)); + } + return snap; } - 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); +#endif + return load_json_db_locked(); +} + +Void::Result::Result +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)", - db_file_.string()))}; + 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(&parsed->value); if (!root_obj) { @@ -364,10 +511,37 @@ StateStore::load_db_locked() const { snap.generations.push_back(std::move(gen)); } } + return snap; +} + +Void::Result::Result +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_->db = *snap; cache_->fp = *cur_fp; cache_->valid = true; } @@ -375,8 +549,88 @@ StateStore::load_db_locked() const { return snap; } +Void::Result::Result +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(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(db); + return std::unexpected{make_error(Void::System::SystemErrorCode::unsupported, + "StateStore: built without Void::Sqlite")}; +#endif +} + Void::Result::Result 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; diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp index 74ae617..1624cfc 100644 --- a/tests/RegistryTests.cpp +++ b/tests/RegistryTests.cpp @@ -228,7 +228,23 @@ VOID_TEST(RegistryTests, registry_rbac_immutability_csrf_xss_web_and_backup_rest if (audit) { Void::Testing::expect(audit->body.find("admin_secret_password") == std::string::npos); Void::Testing::expect(audit->body.find(*alice_tok) == std::string::npos); + Void::Testing::expect(audit->body.find("\"total\":") != std::string::npos); } + auto filtered_audit = send_loopback_http(port, "GET", "/api/v1/audit?limit=1&action=package", + {{"Cookie", cookie}}); + Void::Testing::expect(filtered_audit.has_value() && filtered_audit->status == 200); + if (filtered_audit) { + Void::Testing::expect(filtered_audit->body.find("\"limit\":1") != std::string::npos); + std::size_t action_occurrences = 0; + for (std::size_t pos = filtered_audit->body.find("\"action\":"); pos != std::string::npos; + pos = filtered_audit->body.find("\"action\":", pos + 1)) { + ++action_occurrences; + } + Void::Testing::expect(action_occurrences == 1); + } + auto bad_audit_limit = + send_loopback_http(port, "GET", "/api/v1/audit?limit=5000", {{"Cookie", cookie}}); + Void::Testing::expect(bad_audit_limit.has_value() && bad_audit_limit->status == 400); // Package search pagination: bounded page plus total/limit/offset envelope. auto page = send_loopback_http(port, "GET", "/api/v1/packages?limit=1&offset=0");