From ac08887d8fc1b1a9d54d574c7f73cf0b8c90592a Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 13:17:25 +0300 Subject: [PATCH] feat(worker): drain the queue with parallel workers --- docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/agent-workflow/VERIFICATION.md | 9 +++ docs/roadmap/22-superiority-and-gaps.md | 2 +- src/Main.cpp | 94 ++++++++++++++++-------- tests/RegistryTests.cpp | 98 +++++++++++++++++++++++++ 6 files changed, 176 insertions(+), 30 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 96462f7..6e1330a 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -364,6 +364,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Wave 135 (Remote Action Execution)**: `vbs worker --queue` now executes action specs fetched from the CAS when an action is not built locally - it downloads the declared input blobs (verified), materializes them, runs `command` in `working_directory` (bounded by `--exec-timeout`, default 600 s), stores the declared `output_paths` as CAS blobs, and submits the result record. `RegistryTests.worker_executes_remote_action_spec` seeds a spec (`cat input.txt > output.txt`) and verifies the local output, the CAS record (`exit_code 0`) and the uploaded output blob. +- **Wave 136 (Parallel Worker Drain)**: `vbs worker --queue --parallel N` (1..32) runs N concurrent lease/execute loops in one process; the registry leases each queued action to exactly one worker, so actions are never duplicated. `RegistryTests.worker_parallel_drains_queue_without_duplicates` drains two slow actions with two loops, asserting both started exactly once, overlapped in time, and the queue ended empty. + ## Remaining future scope - **Superiority plan ([22-superiority-and-gaps.md](../roadmap/22-superiority-and-gaps.md), 2026-12-05)**: revised platform strategy - **macOS deferred**, **Windows via MinGW-w64 cross-compilation + Wine execution** (`dev cpp-gcc -p pkgsCross.mingwW64.stdenv.cc`, `dev cpp-gcc -p wine64`), native MSVC deferred; plus packaging parity (ZIP/DEB/RPM), IDE ecosystem, migration tooling, test-runner parity, benchmarks, CI runners, and remote execution in prioritized order. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 8f7799f..42645fc 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -136,4 +136,5 @@ Base HEAD: `fe0d1a6` | Wave 133 (CTest-style fixtures) | `.fixture_setup/required/cleanup` SDK; runner pulls in helpers, orders setup->users->cleanup, skips dependents on failed setup | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E passes, full CTest 8/8) | `include/Void/Build.hpp`, `sdk/Build.cpp`, `src/Main.cpp`, `src/Graph/Graph.cpp`, `tests/FullV1Tests.cpp`, docs | | Wave 134 (CDash reporting) | `Report::Cdash` Test.xml + multipart submission; `vbs test --cdash/--cdash-project/--cdash-build/--cdash-output` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E captures the submission, full CTest 8/8) | `src/Report/Cdash.cpp`, `include/Void/Build/Report/Cdash.hpp`, `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | | Wave 135 (Remote action execution) | Worker fetches input blobs, executes the CAS action spec, stores outputs and submits the result; `--exec-timeout` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E passes, full CTest 8/8) | `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | +| Wave 136 (Parallel worker drain) | `--parallel N` lease/execute loops; exclusive registry leases prevent duplicates | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; E2E proves overlap and no duplicates, full CTest 8/8) | `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | | Future (Plan 20 Slice 3 / Tracks C, E3 editor extensions) |"}] 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 4fcb90a..4796bf0 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1787,6 +1787,15 @@ VOID_INCLUDE_DIR=/tmp/opencode/vl-pin/include dev cpp -c bash fuzz/run.sh 30 `output.txt` and `"exit_code":0`, and the output blob is retrievable with the exact bytes. - Full CTest: **8 / 8 passed** in 301.38 s. +## Parallel Worker Drain (GCC 16.2, pin `0002e74`) + +- `vbs worker --queue --parallel N` starts N lease/execute loops sharing one worker + registration; the registry's exclusive leases guarantee each action runs once. +- `RegistryTests.worker_parallel_drains_queue_without_duplicates` **passed** (836 ms): two + queued actions (`sleep 0.4` each) both started exactly once, their start/end intervals + overlapped (real concurrency), and `GET /api/v1/queue` reported `"pending":[]` afterwards. +- Full CTest: **8 / 8 passed** in 303.93 s. + ## 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/22-superiority-and-gaps.md b/docs/roadmap/22-superiority-and-gaps.md index c2c28cd..32f5adf 100644 --- a/docs/roadmap/22-superiority-and-gaps.md +++ b/docs/roadmap/22-superiority-and-gaps.md @@ -83,7 +83,7 @@ Concrete work this implies: 6. Test-runner parity. 7. Benchmarks against CMake/Meson/build2 on documented fixtures (including 10k-target scaling). 8. CI on real runners, sanitizer jobs (**sanitizer build run done**), parser fuzzing (**deterministic mutation harness and a Clang/libFuzzer target done**). -9. Remote execution workers (**registry worker/lease/result protocol, queue, and remote action execution done**; multi-worker orchestration remains). +9. Remote execution workers (**registry worker/lease/result protocol, queue, remote action execution and parallel workers done**; cross-machine orchestration remains). ## 6. Observed baseline (2026-12-05, x86_64, GCC 16.2, Debug, `benchmarks/compare.sh 20`) diff --git a/src/Main.cpp b/src/Main.cpp index cce017d..19514d5 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -52,6 +52,7 @@ #include #include +#include #include #include #include @@ -1695,6 +1696,7 @@ struct WorkerCmdOptions { std::string token_env{"VBS_REGISTRY_TOKEN"}; std::string lease_seconds_arg{"60"}; std::string exec_timeout_arg{"600"}; + std::string parallel_arg{"1"}; }; int execute_worker_command(const WorkerCmdOptions &opts) { @@ -1975,7 +1977,9 @@ int execute_worker_command(const WorkerCmdOptions &opts) { if (opts.queue_mode && !opts.action_key_arg) { // Continuous loop: lease, process, repeat; exits when the queue is empty (after the - // optional idle timeout) or on --once. + // optional idle timeout) or on --once. --parallel runs several lease/execute loops so + // multiple workers drain the queue concurrently (the registry leases each action to + // exactly one worker). int idle_timeout_seconds = 0; if (!Void::Str::to_int(opts.idle_timeout_arg, idle_timeout_seconds) || idle_timeout_seconds < 0 || idle_timeout_seconds > 3600) { @@ -1983,41 +1987,71 @@ int execute_worker_command(const WorkerCmdOptions &opts) { << "'\n"; return 2; } - const auto idle_deadline = - std::chrono::steady_clock::now() + std::chrono::seconds{idle_timeout_seconds}; - int lease_failures = 0; - while (true) { - auto leased = Package::lease_queued_action(registry, registration->worker_id, - lease_seconds, auth); - if (!leased) { - if (leased.error().kind() == Void::Result::ErrorKind::not_found) { - if (idle_timeout_seconds == 0 || - std::chrono::steady_clock::now() >= idle_deadline) { - std::cout << "queue empty\n"; - return 0; + int parallel_workers = 1; + if (!Void::Str::to_int(opts.parallel_arg, parallel_workers) || parallel_workers < 1 || + parallel_workers > 32) { + std::cerr << "vbs worker: invalid --parallel value '" << opts.parallel_arg + << "' (expected 1..32)\n"; + return 2; + } + std::atomic empty_reported{false}; + std::atomic worker_failed{false}; + const auto drain_queue = [&] { + const auto idle_deadline = + std::chrono::steady_clock::now() + std::chrono::seconds{idle_timeout_seconds}; + int lease_failures = 0; + for (;;) { + if (worker_failed.load(std::memory_order_relaxed)) { + return; + } + auto leased = Package::lease_queued_action(registry, registration->worker_id, + lease_seconds, auth); + if (!leased) { + if (leased.error().kind() == Void::Result::ErrorKind::not_found) { + if (idle_timeout_seconds == 0 || + std::chrono::steady_clock::now() >= idle_deadline) { + if (!empty_reported.exchange(true)) { + std::cout << "queue empty\n"; + } + return; + } + std::this_thread::sleep_for(std::chrono::milliseconds{250}); + continue; } - std::this_thread::sleep_for(std::chrono::milliseconds{250}); + if (++lease_failures > 3) { + std::cerr << "vbs worker: giving up after repeated lease failures: " + << leased.error().message() << '\n'; + worker_failed.store(true); + return; + } + Void::Log::warn("Worker", "lease attempt {} failed: {}", lease_failures, + leased.error().message()); + std::this_thread::sleep_for(std::chrono::milliseconds{100}); continue; } - if (++lease_failures > 3) { - std::cerr << "vbs worker: giving up after repeated lease failures: " - << leased.error().message() << '\n'; - return 1; + lease_failures = 0; + if (const int code = process_leased(*leased); code != 0) { + worker_failed.store(true); + return; + } + if (opts.once) { + return; } - Void::Log::warn("Worker", "lease attempt {} failed: {}", lease_failures, - leased.error().message()); - std::this_thread::sleep_for(std::chrono::milliseconds{100}); - continue; } - lease_failures = 0; - const Package::LeasedAction &queued = *leased; - if (const int code = process_leased(queued); code != 0) { - return code; + }; + if (parallel_workers == 1) { + drain_queue(); + } else { + std::vector pool; + pool.reserve(static_cast(parallel_workers)); + for (int i = 0; i < parallel_workers; ++i) { + pool.emplace_back(drain_queue); } - if (opts.once) { - return 0; + for (auto &thread : pool) { + thread.join(); } } + return worker_failed.load() ? 1 : 0; } auto direct = Package::lease_action(registry, *opts.action_key_arg, registration->worker_id, @@ -3774,7 +3808,9 @@ int main(int argc, char **argv) { .option_default("--lease-seconds", "", "Lease TTL in seconds (1..3600)", worker_opts.lease_seconds_arg, "60") .option_default("--exec-timeout", "", "Remote action timeout in seconds (1..86400)", - worker_opts.exec_timeout_arg, "600"); + worker_opts.exec_timeout_arg, "600") + .option_default("--parallel", "", "Concurrent lease/execute loops in queue mode (1..32)", + worker_opts.parallel_arg, "1"); add_log_flags(worker_cmd); auto &migrate_cmd = root.subcommand( diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp index 727ecca..53c4b8c 100644 --- a/tests/RegistryTests.cpp +++ b/tests/RegistryTests.cpp @@ -2441,3 +2441,101 @@ VOID_TEST(RegistryTests, worker_executes_remote_action_spec) { } (*svc)->stop_http(); } + +// `vbs worker --queue --parallel N`: several lease/execute loops drain the queue concurrently; +// every action runs exactly once. +VOID_TEST(RegistryTests, worker_parallel_drains_queue_without_duplicates) { + const auto vbs_bin = locate_vbs_binary(); + Void::Testing::expect(!vbs_bin.empty() && std::filesystem::exists(vbs_bin)); + if (vbs_bin.empty() || !std::filesystem::exists(vbs_bin)) { + return; + } + Void::FileSystem::TempDir tmp{"vbs_parallel_"}; + RegistryConfig cfg; + cfg.data_dir = tmp / "reg_data"; + cfg.bind_address = "127.0.0.1"; + cfg.port = 0; + cfg.bootstrap_admin_user = "admin"; + cfg.bootstrap_admin_password = "admin_pw"; + auto svc = RegistryService::open(cfg); + Void::Testing::expect(svc.has_value()); + if (!svc) { + return; + } + Void::Testing::expect((*svc)->create_user("par_pub", "par_pass", Role::Publisher).has_value()); + auto tok = (*svc)->create_token("par_pub", "par", {"read", "publish"}); + Void::Testing::expect(tok.has_value()); + if (!tok) { + return; + } + Void::Testing::expect((*svc)->start_http().has_value()); + const auto port = (*svc)->bound_port(); + const std::string reg_url = "http://127.0.0.1:" + std::to_string(port); + const std::map> auth{{"Authorization", "Bearer " + *tok}}; + + const auto workdir = tmp / "workdir"; + std::filesystem::create_directories(workdir); + std::vector keys; + for (const char *name : {"alpha", "beta"}) { + const std::string key = Util::sha256_hex(std::string{"parallel-"} + name); + keys.push_back(key); + const std::string spec = "{\"schema_version\":1,\"action_key\":\"" + key + + "\",\"command\":[\"/bin/sh\",\"-c\",\"echo start-" + name + + " >> order.log; sleep 0.4; echo end-" + name + + " >> order.log\"],\"working_directory\":\"" + workdir.string() + + "\",\"output_paths\":[]}"; + auto put = send_loopback_http(port, "PUT", "/api/v1/cas/actions/" + key, auth, spec); + Void::Testing::expect(put.has_value() && put->status == 201); + } + auto enqueued = + send_loopback_http(port, "POST", "/api/v1/queue", auth, + "{\"action_keys\":[\"" + keys[0] + "\",\"" + keys[1] + "\"]}"); + Void::Testing::expect(enqueued.has_value() && enqueued->status == 200); + + Platform::ProcessRequest worker; + worker.executable = vbs_bin; + worker.arguments = {"worker", "--registry", reg_url, "--queue", + "--parallel", "2", "--build-dir", (tmp / "build").string()}; + worker.environment.set_vars["VBS_REGISTRY_TOKEN"] = *tok; + worker.timeout = std::chrono::seconds{120}; + auto worker_res = Platform::run_supervised(worker); + Void::Testing::expect_eq( + worker_res ? (worker_res->succeeded() ? std::string{} + : (worker_res->stdout_data + worker_res->stderr_data)) + : worker_res.error().message(), + std::string{}); + + auto order_text = Void::FileSystem::read_file(workdir / "order.log"); + Void::Testing::require(order_text.has_value()); + std::set running; + std::set started; + std::set ended; + bool overlap = false; + for (std::size_t pos = 0; pos < order_text->size();) { + const auto eol = order_text->find('\n', pos); + const std::string line = order_text->substr(pos, eol - pos); + pos = eol == std::string::npos ? order_text->size() : eol + 1; + if (line.starts_with("start-")) { + const std::string name = line.substr(6); + Void::Testing::expect(started.insert(name).second); // never leased twice + if (!running.empty()) { + overlap = true; + } + running.insert(name); + } else if (line.starts_with("end-")) { + const std::string name = line.substr(4); + ended.insert(name); + running.erase(name); + } + } + Void::Testing::expect_eq(started.size(), std::size_t{2}); + Void::Testing::expect_eq(ended.size(), std::size_t{2}); + Void::Testing::expect(overlap); // the two actions ran concurrently + + auto queue_state = send_loopback_http(port, "GET", "/api/v1/queue", auth); + Void::Testing::expect(queue_state.has_value() && queue_state->status == 200); + if (queue_state) { + Void::Testing::expect(queue_state->body.find("\"pending\":[]") != std::string::npos); + } + (*svc)->stop_http(); +}