From 55bc0529b9a4c5632c6b880ee7873adaa50dcdce Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 12:03:46 +0300 Subject: [PATCH] feat(worker): renew leases and watch an idle queue --- docs/agent-workflow/STATE.md | 2 + docs/agent-workflow/TASKS.md | 1 + docs/agent-workflow/VERIFICATION.md | 6 +++ include/Void/Build/Package/RegistryClient.hpp | 6 +++ registry/service/RegistryService.cpp | 33 ++++++++++++ src/Main.cpp | 54 +++++++++++++------ src/Package/RegistryClient.cpp | 33 ++++++++++++ tests/RegistryTests.cpp | 34 ++++++++++++ 8 files changed, 152 insertions(+), 17 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 8542a59..6ae3df0 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -348,6 +348,8 @@ Stage: VERIFIED — Plans 01–19 + Plan 20 Slices 1–2C + Track A + Track B (B - **Wave 127 (Continuous Worker Loop)**: `vbs worker --queue` now loops - lease, process, repeat - exiting when the queue is empty (or after one action with `--once`). In loop mode the record is exported from the local state store (`--record` is optional), transient lease failures are retried three times, and actions that are not built locally are skipped with a warning. The worker E2E exercises the loop and asserts the `queue empty` exit. +- **Wave 128 (Lease Renewal & Idle-Timeout Watcher)**: the registry gained `POST /api/v1/actions//renew` (token-checked lease extension, bounded TTL, audited) and `Package::renew_action_lease`. `vbs worker --queue` accepts `--idle-timeout SECONDS` to keep watching an empty queue before exiting, and `--once` now limits the loop to one action. The worker E2E asserts the idle wait, renewal success, and wrong-token rejection. + ## 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 e648506..f7f532d 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -130,4 +130,5 @@ Base HEAD: `fe0d1a6` | Wave 125 (`vbs worker --queue`) | Queue-driven worker lease mode with `lease_queued_action`; E2E covers both modes | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; worker E2E passes, full CTest 8/8) | `src/Main.cpp`, `src/Package/RegistryClient.cpp`, `include/Void/Build/Package/RegistryClient.hpp`, `tests/RegistryTests.cpp`, docs | | Wave 126 (VoidLibrary test wiring) | Per-module package tests declared in the branch build.cpp; CI runs `vbs test` | COMPLETE & VERIFIED IN CLONE (156 actions; module test binaries PASSED, exit 0) | [Void/Library build-vbs](https://git.faumaray.com/Void/Library/src/branch/build-vbs), `contrib/voidlibrary-migration/`, docs | | Wave 127 (Continuous worker loop) | `vbs worker --queue` loop with local record export, retries, skip-on-missing, `--once`, exit on empty queue | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; worker E2E passes, full CTest 8/8) | `src/Main.cpp`, `tests/RegistryTests.cpp`, docs | +| Wave 128 (Lease renewal + idle timeout) | `actions//renew`, `renew_action_lease`, `worker --idle-timeout/--once` | COMPLETE & VERIFIED (GCC 16.2, pin `0002e74`; worker E2E passes, full CTest 8/8) | `registry/service/RegistryService.cpp`, `src/Package/RegistryClient.cpp`, `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 5e898d7..fd53476 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -1721,6 +1721,12 @@ VOID_INCLUDE_DIR=/tmp/opencode/vl-pin/include dev cpp -c bash fuzz/run.sh 30 - `RegistryTests.worker_cli_leases_publishes_and_reports_result` **passed** (506 ms), covering direct, single queue and continuous loop modes; the loop output contains the action key and `queue empty`. - Full CTest: **8 / 8 passed** in 294.19 s. +## Lease Renewal & Idle Timeout (GCC 16.2, pin `0002e74`) + +- `POST /api/v1/actions//renew` extends a live lease when the token matches (403 otherwise, 409 when unleased), and `vbs worker --idle-timeout N` keeps watching an empty queue for N seconds (exit 0 afterwards); `--once` stops after one action. +- `RegistryTests.worker_cli_leases_publishes_and_reports_result` **passed** (1.54 s): the idle worker ran for >= 900 ms, renewal succeeded, and a wrong token was rejected. +- Full CTest: **8 / 8 passed** in 302.11 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/include/Void/Build/Package/RegistryClient.hpp b/include/Void/Build/Package/RegistryClient.hpp index c9e71ed..ebb144c 100644 --- a/include/Void/Build/Package/RegistryClient.hpp +++ b/include/Void/Build/Package/RegistryClient.hpp @@ -76,6 +76,12 @@ lease_action(std::string_view registry_url, std::string_view action_key, std::st lease_queued_action(std::string_view registry_url, std::string_view worker_id, std::int64_t lease_seconds, const RegistryAuth &auth = {}); +// Renews an active lease; returns the new expiry epoch. +[[nodiscard]] Void::Result::Result +renew_action_lease(std::string_view registry_url, std::string_view action_key, + std::string_view lease_token, std::int64_t lease_seconds, + const RegistryAuth &auth = {}); + [[nodiscard]] Void::Result::Result submit_action_result(std::string_view registry_url, std::string_view action_key, std::string_view lease_token, std::string_view record_json, diff --git a/registry/service/RegistryService.cpp b/registry/service/RegistryService.cpp index b7d8b44..f1174bb 100644 --- a/registry/service/RegistryService.cpp +++ b/registry/service/RegistryService.cpp @@ -1191,6 +1191,39 @@ HttpResponse RegistryService::handle_request(const HttpRequest &req) { ",\"record\":" + *record_text + "}\n"); } + if (segs.size() == 5 && segs[4] == "renew" && req.method == "POST") { + const std::string &action_key = segs[3]; + prune_expired_leases(); + const auto lease_it = action_leases_.find(action_key); + if (lease_it == action_leases_.end()) { + return HttpResponse::error_json(409, "not_leased", "action has no active lease"); + } + auto parsed = Void::Json::Strict::parse(req.body); + const auto *obj = parsed ? std::get_if(&parsed->value) : nullptr; + if (obj == nullptr) { + return HttpResponse::error_json(400, "invalid_json", "renew body must be JSON"); + } + if (get_str(*obj, "lease_token") != lease_it->second.lease_token) { + return HttpResponse::error_json(403, "invalid_lease_token", + "lease token does not match"); + } + std::int64_t lease_seconds = 60; + if (const auto it = obj->find("lease_seconds"); it != obj->end()) { + const auto *value = std::get_if(&it->second.value); + if (!value || *value <= 0 || *value > 3600) { + return HttpResponse::error_json(400, "invalid_lease", + "lease_seconds must be 1..3600"); + } + lease_seconds = *value; + } + lease_it->second.expires_epoch = now_epoch() + lease_seconds; + append_audit_locked(principal->username, "action.renew", action_key, "ok", ""); + return HttpResponse::json( + 200, std::format("{{\"action_key\":{},\"lease_token\":{},\"expires_epoch\":{}}}\n", + json_quote(action_key), json_quote(lease_it->second.lease_token), + lease_it->second.expires_epoch)); + } + if (segs.size() == 5 && segs[4] == "result" && req.method == "POST") { const std::string &action_key = segs[3]; if (!is_sha256_hex(action_key)) { diff --git a/src/Main.cpp b/src/Main.cpp index 5f43aee..1d52157 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1455,6 +1455,7 @@ struct WorkerCmdOptions { std::optional record_arg; bool queue_mode{false}; bool once{false}; + std::string idle_timeout_arg{"0"}; std::string project_arg; std::optional build_arg; std::string token_env{"VBS_REGISTRY_TOKEN"}; @@ -1575,29 +1576,44 @@ 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 or on --once. + // Continuous loop: lease, process, repeat; exits when the queue is empty (after the + // optional idle timeout) or on --once. + 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) { + std::cerr << "vbs worker: invalid --idle-timeout value '" << opts.idle_timeout_arg + << "'\n"; + return 2; + } + const auto idle_deadline = + std::chrono::steady_clock::now() + std::chrono::seconds{idle_timeout_seconds}; + int lease_failures = 0; while (true) { - std::optional queued; - for (int attempt = 0; attempt < 3 && !queued; ++attempt) { - auto leased = Package::lease_queued_action(registry, registration->worker_id, - lease_seconds, auth); - if (leased) { - queued = std::move(*leased); - break; - } + auto leased = Package::lease_queued_action(registry, registration->worker_id, + lease_seconds, auth); + if (!leased) { if (leased.error().kind() == Void::Result::ErrorKind::not_found) { - std::cout << "queue empty\n"; - return 0; + if (idle_timeout_seconds == 0 || + std::chrono::steady_clock::now() >= idle_deadline) { + std::cout << "queue empty\n"; + return 0; + } + std::this_thread::sleep_for(std::chrono::milliseconds{250}); + continue; } - Void::Log::warn("Worker", "lease attempt {} failed: {}", attempt + 1, + if (++lease_failures > 3) { + std::cerr << "vbs worker: giving up after repeated lease failures: " + << leased.error().message() << '\n'; + return 1; + } + Void::Log::warn("Worker", "lease attempt {} failed: {}", lease_failures, leased.error().message()); std::this_thread::sleep_for(std::chrono::milliseconds{100}); + continue; } - if (!queued) { - std::cerr << "vbs worker: giving up after repeated lease failures\n"; - return 1; - } - if (const int code = process_leased(*queued); code != 0) { + lease_failures = 0; + const Package::LeasedAction &queued = *leased; + if (const int code = process_leased(queued); code != 0) { return code; } if (opts.once) { @@ -3340,6 +3356,10 @@ int main(int argc, char **argv) { .option("--record", "", "Action record JSON file to publish", worker_opts.record_arg) .flag("--queue", "", "Lease the next action from the registry queue", worker_opts.queue_mode) + .flag("--once", "", "Process at most one queued action", worker_opts.once) + .option_default("--idle-timeout", "", + "Seconds to wait for new queued work before exiting (0 = exit)", + worker_opts.idle_timeout_arg, "0") .option_default("--project", "-C", "Project directory", worker_opts.project_arg, cwd) .option("--build-dir", "-B", "Build directory", worker_opts.build_arg) .option_default("--token-env", "", "Environment variable holding bearer token", diff --git a/src/Package/RegistryClient.cpp b/src/Package/RegistryClient.cpp index 93c4a6a..3433d21 100644 --- a/src/Package/RegistryClient.cpp +++ b/src/Package/RegistryClient.cpp @@ -950,6 +950,39 @@ lease_queued_action(std::string_view registry_url, std::string_view worker_id, return leased; } +Void::Result::Result +renew_action_lease(std::string_view registry_url, std::string_view action_key, + std::string_view lease_token, std::int64_t lease_seconds, + const RegistryAuth &auth) { + auto parsed_url = parse_registry_url(registry_url); + if (!parsed_url) { + return std::unexpected{parsed_url.error()}; + } + const std::string path = + "/api/v1/actions/" + Void::Encoding::Url::encode(action_key) + "/renew"; + const std::string body = std::format("{{\"lease_token\":{},\"lease_seconds\":{}}}", + json_quote_of(lease_token), lease_seconds); + auto reply = send_http_request(*parsed_url, "POST", path, bearer_headers(auth), body); + if (!reply) { + return std::unexpected{reply.error()}; + } + if (reply->status != 200) { + return std::unexpected{make_error( + reply->status == 409 ? Void::System::SystemErrorCode::busy + : reply->status == 403 ? Void::System::SystemErrorCode::permission_denied + : reply->status == 400 ? Void::System::SystemErrorCode::invalid_argument + : Void::System::SystemErrorCode::io_error, + std::format("lease renewal failed with HTTP {}: {}", reply->status, reply->body))}; + } + auto json = Void::Json::Strict::parse(reply->body); + const auto *object = json ? std::get_if(&json->value) : nullptr; + if (!object) { + return std::unexpected{ + make_error(Void::System::SystemErrorCode::io_error, "invalid lease renewal response")}; + } + return get_i64(*object, "expires_epoch", 0); +} + Void::Result::Result submit_action_result(std::string_view registry_url, std::string_view action_key, std::string_view lease_token, diff --git a/tests/RegistryTests.cpp b/tests/RegistryTests.cpp index 0cc188e..f690281 100644 --- a/tests/RegistryTests.cpp +++ b/tests/RegistryTests.cpp @@ -2170,6 +2170,40 @@ VOID_TEST(RegistryTests, worker_cli_leases_publishes_and_reports_result) { Void::Testing::expect(loop_res->stdout_data.find("queue empty") != std::string::npos); Void::Testing::expect(loop_res->stdout_data.find(action_key) != std::string::npos); } + + // Idle timeout: an empty queue keeps the worker alive for the configured time. + Platform::ProcessRequest idle_worker = loop_worker; + idle_worker.arguments.push_back("--idle-timeout"); + idle_worker.arguments.push_back("1"); + const auto idle_start = std::chrono::steady_clock::now(); + auto idle_res = Platform::run_supervised(idle_worker); + const auto idle_elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - idle_start); + Void::Testing::expect(idle_res.has_value() && idle_res->succeeded()); + Void::Testing::expect(idle_elapsed >= std::chrono::milliseconds{900}); + + // Lease renewal extends a live lease and rejects a wrong token. + auto enqueued_once_more = send_loopback_http(port, "POST", "/api/v1/queue", auth, + "{\"action_keys\":[\"" + action_key + "\"]}"); + Void::Testing::expect(enqueued_once_more.has_value() && enqueued_once_more->status == 200); + auto renew_worker = send_loopback_http(port, "POST", "/api/v1/workers", auth, "{}"); + Void::Testing::require(renew_worker.has_value() && renew_worker->status == 201); + const std::string renew_worker_id = extract_json_str(renew_worker->body, "worker_id"); + auto lease_for_renew = + send_loopback_http(port, "POST", "/api/v1/queue/lease", auth, + "{\"worker_id\":\"" + renew_worker_id + "\",\"lease_seconds\":1}"); + Void::Testing::require(lease_for_renew.has_value() && lease_for_renew->status == 200); + const std::string renew_token = extract_json_str(lease_for_renew->body, "lease_token"); + auto wrong_renew = send_loopback_http(port, "POST", "/api/v1/actions/" + action_key + "/renew", + auth, "{\"lease_token\":\"deadbeef\"}"); + Void::Testing::expect(wrong_renew.has_value() && wrong_renew->status == 403); + auto renewed = + send_loopback_http(port, "POST", "/api/v1/actions/" + action_key + "/renew", auth, + "{\"lease_token\":\"" + renew_token + "\",\"lease_seconds\":120}"); + Void::Testing::expect(renewed.has_value() && renewed->status == 200); + if (renewed) { + Void::Testing::expect(renewed->body.find("expires_epoch") != std::string::npos); + } (*svc)->stop_http(); }