// The function runner binary. // // It is the second process of the design in // docs/superpowers/specs/2026-10-06-function-runtime-design.md: vectorapi // routes and schedules, the runner executes. Everything interesting about the // protocol lives in run_service.{hpp,cpp}; this file is wiring - config, // logging, the database connection, the two seams RunService takes, and a // cpp-httplib server that does nothing but shuttle JSON between them. // // It deliberately holds the only code here that links vectorapi_core and the // database client, which is what keeps run_service testable on a host where // that client cannot compile at all (CLAUDE.md). #include "db_gateway.hpp" #include "errors.hpp" #include "function_env.hpp" #include "function_jobs.hpp" #include "job_worker.hpp" #include "project_secret_store.hpp" #include "function_record.hpp" #include "runner_auth.hpp" #include "function_registry.hpp" #include "project_settings.hpp" #include "run_service.hpp" #include "runner/host_context.hpp" #include "settings_store.hpp" #include #include #include #include #ifdef HAVE_SYSTEMD #include #else #define sd_notify(u, s) do {} while (0) #endif #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { std::atomic g_running{true}; void onSignal(int) { g_running = false; } /// The runner's own bootstrap config. Separate from svapi::Config because the /// two processes need different things: no web UI here, but the per-run /// ceilings and the pool size, which an operator sizes against the host. /// /// Same posture as the server's config though: minimal, and only what has to be /// known BEFORE the database is reachable. Anything that can hot-reload belongs /// in the database, not here. /// /// The `runtime` ceilings are deliberately BOOT-TIME ONLY, unlike every /// hot-reloading setting in the server. QuickJS fixes a runtime's memory limit /// when the runtime is created, so changing it live would mean draining and /// recreating every pooled runtime - real complexity for a knob that is a /// host-sizing decision, not something an operator tunes while watching a /// dashboard. Editing these means `systemctl restart /// smartbotic-vectorapi-runner`, which is cheap: vectorapi answers 503 for the /// moment the runner is down and nothing is stored unvalidated. /// /// The ONE value that has to stay in step with the server is /// `max_wall_time_ms`, the ceiling for HTTP-triggered runs: RunnerPool's /// readTimeoutSec must exceed it, or our read times out before the runner can /// report its own timeout and a caller gets a misleading 503 instead of a 504. /// The JOB ceiling is deliberately not bound by that number - a job run is /// claimed from the queue inside this process and no socket is waiting on it. struct RunnerConfig { std::string logLevel = "info"; /// Loopback by default: the single-host deployment, where no token is /// needed because nothing else can reach the port. Binding anywhere else /// REQUIRES a token - see startupRefusal(). std::string httpBind = "127.0.0.1"; /// Shared secret vectorapi presents as `Authorization: Bearer`. Prefer /// SVAPI_RUNNER_TOKEN in runner.env, which can be mode 0640; this config /// file is a conffile and tends to be world-readable. std::string authToken; uint16_t httpPort = 8090; std::string dbAddress = "localhost:9004"; size_t poolSize = 4; size_t memoryLimitBytes = 128u * 1024 * 1024; /// Ceiling for a run an HTTP request triggered. Kept at two seconds: a /// client is waiting on it, and vectorapi's read timeout is sized against /// this number. int64_t maxWallTimeMs = 2000; /// Ceiling for a run the job queue triggered (cron, database events). Two /// minutes, because that is what the work is: an LLM call takes seconds to /// tens of seconds and an uncached embedding search has been measured at /// 26 s, and none of it has a client waiting on a socket. int64_t maxJobWallTimeMs = 120000; /// Applied when a descriptor declares no timeoutMs. 0 = use whichever /// ceiling applies to the run. int64_t defaultWallTimeMs = 0; /// How long a project's wall-time maximum is cached before it is re-read. /// Not subscribed to, unlike the server's settings: one read per project /// per interval is nothing, and a per-run read would put two round trips on /// the hot path for a number that changes by hand. int projectBudgetTtlSec = 15; size_t maxStackBytes = 512u * 1024; size_t bytecodeCacheEntries = 64; /// Runtimes reserved for job runs. A separate lane, so a cron job holding a /// runtime for its whole 120 s ceiling cannot take the one an interactive /// route is about to need. Costs memory: the per-run ceiling is per /// runtime, so this adds to poolSize rather than dividing it. size_t jobPoolSize = 4; /// Claiming queued work is OFF by default: a runner upgrade must not start /// draining a queue in a deployment whose server has no scheduler. bool jobsEnabled = false; uint32_t jobWorkers = 0; ///< 0 = jobPoolSize - 1, never below 1 uint32_t jobMaxAttempts = 5; uint32_t staleClaimSec = 300; /// How long a single /run or /validate request may occupy a server thread. /// Above the wall-time ceiling on purpose: a run that is about to be killed /// should report its own timeout rather than have the socket cut first. int readTimeoutSec = 30; static RunnerConfig fromJson(const nlohmann::json& j) { RunnerConfig c; c.logLevel = j.value("log_level", c.logLevel); if (j.contains("http") && j["http"].is_object()) { const auto& h = j["http"]; c.httpBind = h.value("bind_address", c.httpBind); c.httpPort = h.value("port", c.httpPort); c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec); c.authToken = h.value("auth_token", c.authToken); } if (j.contains("jobs") && j["jobs"].is_object()) { const auto& jb = j["jobs"]; c.jobsEnabled = jb.value("enabled", c.jobsEnabled); c.jobWorkers = jb.value("workers", c.jobWorkers); c.jobMaxAttempts = jb.value("max_attempts", c.jobMaxAttempts); c.staleClaimSec = jb.value("stale_claim_sec", c.staleClaimSec); } if (j.contains("database") && j["database"].is_object()) c.dbAddress = j["database"].value("address", c.dbAddress); if (j.contains("runtime") && j["runtime"].is_object()) { const auto& r = j["runtime"]; c.poolSize = r.value("pool_size", c.poolSize); c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes); // `max_wall_time_ms` keeps its old name and its old meaning - the // HTTP ceiling - so an existing conffile is not silently // reinterpreted. `max_http_wall_time_ms` is the clearer spelling // and wins when both are present. c.maxWallTimeMs = r.value("max_wall_time_ms", c.maxWallTimeMs); c.maxWallTimeMs = r.value("max_http_wall_time_ms", c.maxWallTimeMs); c.maxJobWallTimeMs = r.value("max_job_wall_time_ms", c.maxJobWallTimeMs); c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs); c.projectBudgetTtlSec = r.value("project_budget_ttl_sec", c.projectBudgetTtlSec); c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes); c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries); c.jobPoolSize = r.value("job_pool_size", c.jobPoolSize); } return c; } static RunnerConfig load(const std::string& path) { std::ifstream f(path); if (!f) throw std::runtime_error("cannot open config file: " + path); nlohmann::json j; f >> j; return fromJson(j); } }; /// One project's admin-set wall-time maximum, cached for a few seconds. /// /// Read straight through the gateway rather than through SettingsStore, for the /// reason HostContext gives for doing the same: the store's bootstrap() WRITES, /// seeding the settings document, which a runner must never do to configuration /// it is only reading. The precedence itself stays in the one pure /// maxFunctionWallTimeMsFor(). class ProjectWallMaxCache { public: ProjectWallMaxCache(svapi::DbGateway& db, int ttlSec) : db_(db), ttl_(std::chrono::seconds(ttlSec < 1 ? 1 : ttlSec)) {} int64_t get(const std::string& project) { const auto now = std::chrono::steady_clock::now(); { std::lock_guard lock(mu_); auto it = entries_.find(project); if (it != entries_.end() && now < it->second.expires) return it->second.valueMs; } int64_t valueMs = 0; bool read = false; try { const std::string coll = svapi::qualify("default", svapi::kSettingsCollection); if (auto doc = db_.client().get(coll, svapi::projectSettingsDocId(project))) { const svapi::ProjectSettings p = svapi::ProjectSettings::fromJson(*doc); valueMs = svapi::maxFunctionWallTimeMsFor(&p); } read = true; } catch (const std::exception& e) { // A failed read must not silently remove a project's cap, so the // last known value is kept and only its expiry is pushed out. With // nothing known yet the run falls back to the configured ceiling, // which still bounds it - the project maximum can only narrow. spdlog::warn("could not read the wall-time maximum for project {} - {}", project, e.what()); } std::lock_guard lock(mu_); auto it = entries_.find(project); if (!read && it != entries_.end()) { it->second.expires = now + ttl_; return it->second.valueMs; } entries_[project] = Entry{valueMs, now + ttl_}; return valueMs; } private: struct Entry { int64_t valueMs = 0; std::chrono::steady_clock::time_point expires{}; }; svapi::DbGateway& db_; std::chrono::steady_clock::duration ttl_; std::mutex mu_; std::map entries_; }; /// RunService's registry seam, over the real FunctionRegistry. /// /// The whole adapter is this one translation, which is the point: the protocol /// layer never learns that a database exists, and this class holds no logic a /// test would want to reach. /// ctx.jobs, over the real queue. /// /// The authorization rule lives HERE rather than in the host context, because /// it needs the registry and the host context deliberately does not: a function /// may only enqueue something a caller could otherwise reach. Without this a /// script could schedule a disabled or invalid function, or name an id that /// does not exist and get a row nothing will ever drain. class QueueJobPort : public svapi::runner::JobPort { public: QueueJobPort(svapi::FunctionJobQueue& queue, svapi::FunctionRegistry& registry) : queue_(queue), registry_(registry) {} std::string enqueue(const std::string& project, const std::string& functionId, const nlohmann::json& trigger, uint64_t runAfterEpochSec, uint32_t depth, const std::string& jobId) override { // Same rule /fn/{project}/* applies: absent, disabled and invalid are // one answer to a caller, so a script learns nothing about which. const std::optional target = registry_.get(project, functionId); if (!target || !target->enabled || !target->valid) throw svapi::ApiError(svapi::ErrCode::NotFound, "not_found", "no enabled function '" + functionId + "' in this project"); svapi::FunctionJob job; job.jobId = jobId; // empty: the queue mints one job.project = project; job.functionId = functionId; job.trigger = "job"; job.payload = trigger; job.depth = depth; job.runAfter = runAfterEpochSec; const std::string id = queue_.enqueue(job); if (id.empty()) throw svapi::ApiError(svapi::ErrCode::Unavailable, "enqueue_failed", "the job could not be queued"); return id; } bool cancel(const std::string& project, const std::string& jobId) override { const std::optional job = queue_.get(jobId); if (!job) return false; // Project checked against the ROW, not taken from the caller: a job id // is global, so a matching id in another tenant's queue must not be // cancellable from here. if (job->project != project) return false; // A claimed job may be executing this instant. Deleting the row would // not stop the run, and would leave the runner completing a job that no // longer exists. if (job->state == "claimed") return false; return queue_.remove(jobId); } private: svapi::FunctionJobQueue& queue_; svapi::FunctionRegistry& registry_; }; class RegistryFunctionSource : public svapi::runner::FunctionSource { public: RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMaxCache& budgets) : registry_(registry), budgets_(budgets) {} svapi::runner::FunctionView lookup(const std::string& project, const std::string& functionId) override { svapi::runner::FunctionView view; std::optional row; try { row = registry_.get(project, functionId); } catch (const std::exception& e) { // A database failure is not a missing function, but the /run // contract has no third answer. Logged loudly so the two are // distinguishable in the journal even though the caller sees a 404. spdlog::error("registry read failed for {}:{} - {}", project, functionId, e.what()); return view; } if (!row) return view; view.found = true; view.source = row->source; view.contentHash = row->contentHash; view.descriptor = row->descriptor; view.policy = row->policy; view.enabled = row->enabled; view.valid = row->valid; view.lastError = row->lastError; view.projectMaxWallTimeMs = budgets_.get(project); return view; } private: svapi::FunctionRegistry& registry_; ProjectWallMaxCache& budgets_; }; /// RunService's ctx seam, over the real HostContext. class GatewayHostBindings : public svapi::runner::HostBindingsFactory { public: GatewayHostBindings(svapi::DbGateway& db, std::vector environment, std::shared_ptr jobs) : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)) {} bool create(const Request& request, svapi::runner::HostBindingsLease& out, std::string& error) override { svapi::runner::HostContextConfig cfg; cfg.project = request.project; cfg.functionId = request.functionId; cfg.policy = request.policy; cfg.trigger = request.trigger; cfg.deadlineMs = request.deadlineMs; // Only this project's secrets, from the runner's own environment // (systemd loads runner.env). The project is part of each variable's // name, because one runner serves every project and nothing else would // keep one tenant's key away from another's script. // Read per run, not cached: a cached secret is a rotated credential // that keeps working. A database failure here throws, which create() // turns into "host context unavailable" - better than a run that // silently proceeds without its credentials. cfg.jobs = jobs_; cfg.env = svapi::runner::functionEnvFor(request.project, environment_, svapi::ProjectSecretStore(db_).valuesFor( request.project)); try { auto host = std::make_unique(db_, std::move(cfg)); svapi::runner::HostContext* raw = host.get(); out.bindings = std::move(host); out.collectConsole = [raw] { std::vector lines = raw->logLines(); // Refused egress is reported as console output rather than // swallowed: a blocked fetch otherwise reaches the author // looking like an ordinary network error he will debug forever. for (const auto& blocked : raw->blockedEgress()) lines.push_back("egress blocked: " + blocked); return lines; }; return true; } catch (const std::exception& e) { error = std::string("host context unavailable: ") + e.what(); return false; } } private: svapi::DbGateway& db_; std::vector environment_; /// Null when the queue is not available, which ctx.jobs reports as /// `jobs_unavailable` rather than pretending to enqueue. std::shared_ptr jobs_; }; /// Parse a request body, or answer 400 with the same error envelope the rest of /// the protocol uses. bool readJsonBody(const httplib::Request& req, httplib::Response& res, nlohmann::json& out) { try { out = nlohmann::json::parse(req.body.empty() ? "{}" : req.body); } catch (const std::exception& e) { res.status = 400; res.set_content(nlohmann::json{{"ok", false}, {"error", std::string("invalid JSON body: ") + e.what()}} .dump(), "application/json"); return false; } return true; } void reply(httplib::Response& res, const svapi::runner::ProtocolResponse& out) { res.status = out.httpStatus; res.set_content(out.body.dump(), "application/json"); } } // namespace int main(int argc, char** argv) { std::string configPath = "/etc/smartbotic-vectorapi/runner.json"; for (int i = 1; i < argc; ++i) { if (std::strcmp(argv[i], "--config") == 0 && i + 1 < argc) configPath = argv[++i]; else if (std::strcmp(argv[i], "--version") == 0 || std::strcmp(argv[i], "-v") == 0) { std::cout << "smartbotic-vectorapi-runner " << svapi::VERSION << " (" << svapi::GIT_COMMIT << ")\n"; return 0; } } RunnerConfig cfg; try { cfg = RunnerConfig::load(configPath); } catch (const std::exception& e) { std::cerr << "config error: " << e.what() << "\n"; return 1; } spdlog::set_level(spdlog::level::from_str(cfg.logLevel)); std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN); svapi::DbGateway db(cfg.dbAddress); spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress); for (int i = 0; i < 30 && !db.connect(); ++i) std::this_thread::sleep_for(std::chrono::seconds(1)); if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; } svapi::FunctionRegistry registry(db); // Re-open every project's function collection. The database only surfaces a // collection through find()/list() once it has been opened in the current // process, so without this a restart leaves every function invisible even // though the rows survive - the same trap CollectionRegistry::bootstrap and // KeyStore::bootstrap exist for. { auto projects = db.listProjects(); registry.bootstrap(projects); spdlog::info("opened the function registry for {} project(s)", projects.size()); } svapi::runner::RunServiceOptions options; options.poolSize = cfg.poolSize; options.limits.memory_limit_bytes = cfg.memoryLimitBytes; options.httpWallCeilingMs = cfg.maxWallTimeMs; options.jobWallCeilingMs = cfg.maxJobWallTimeMs; // The engine's hard ceiling is raised to the highest of the two by // RunService itself; setting it from the HTTP ceiling here would cap every // job run at the HTTP budget. options.limits.wall_time_ms = cfg.maxWallTimeMs; options.limits.max_stack_bytes = cfg.maxStackBytes; options.defaultTimeoutMs = cfg.defaultWallTimeMs; options.bytecodeCacheEntries = cfg.bytecodeCacheEntries; options.version = svapi::VERSION; options.jobPoolSize = cfg.jobPoolSize; ProjectWallMaxCache projectBudgets(db, cfg.projectBudgetTtlSec); RegistryFunctionSource source(registry, projectBudgets); // The queue has to exist before the bindings that enqueue into it. ensure() // is idempotent and also re-opens the collection, without which find() // cannot see existing rows in this process. svapi::FunctionJobQueue jobQueue(db); jobQueue.ensure(); auto jobPort = std::make_shared(jobQueue, registry); // Snapshot the environment once: it does not change under a running // process, and re-reading it per run would be work for no gain. GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort); svapi::runner::RunService service(source, options, &host); // The environment wins over the config file: a secret belongs in // runner.env, which systemd can keep at mode 0640, not in a conffile. std::string authToken = cfg.authToken; if (const char* fromEnv = std::getenv(svapi::runner::kRunnerTokenEnvVar); fromEnv != nullptr && *fromEnv != '\0') { authToken = fromEnv; } if (const auto refusal = svapi::runner::startupRefusal(cfg.httpBind, authToken)) { spdlog::critical("{}", *refusal); return 1; } if (authToken.empty()) { spdlog::warn("no runner token set; serving unauthenticated on {} - safe only" " because nothing off this host can reach it", cfg.httpBind); } httplib::Server server; server.set_read_timeout(cfg.readTimeoutSec, 0); server.set_write_timeout(cfg.readTimeoutSec, 0); // The pool already bounds concurrency; matching the thread count to it // keeps requests waiting in the accept queue instead of piling up threads // that all block on acquire(). server.new_task_queue = [&cfg] { return new httplib::ThreadPool(static_cast(cfg.poolSize) + 2); }; // Authenticate everything, /health included. The health check is what // vectorapi uses to decide a runner is usable, and it reports the pool's // state - neither is something an unauthenticated caller should see. if (!authToken.empty()) { server.set_pre_routing_handler( [&authToken](const httplib::Request& req, httplib::Response& res) { const std::string presented = svapi::runner::bearerToken(req.get_header_value("Authorization")); if (svapi::runner::tokenMatches(authToken, presented)) return httplib::Server::HandlerResponse::Unhandled; res.status = 401; res.set_content(R"({"error":{"code":"unauthorized","message":)" R"("missing or invalid runner token"}})", "application/json"); return httplib::Server::HandlerResponse::Handled; }); } server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) { nlohmann::json body; if (!readJsonBody(req, res, body)) return; // The kind of run is the caller's statement, not a guess: only the // caller knows whether a socket is waiting on this. Absent or // unrecognised means HTTP, the short budget, because that is the // mistake that costs a slow run rather than a pinned runtime. A // forged "job" buys nothing an attacker wants either, and this port is // token-authenticated and reachable only by vectorapi. const std::string kindName = body.is_object() && body.contains("kind") && body.at("kind").is_string() ? body.at("kind").get() : std::string(); reply(res, service.run(body, svapi::functions::parseRunKind( kindName, svapi::functions::RunKind::Http))); }); server.Post("/validate", [&service](const httplib::Request& req, httplib::Response& res) { nlohmann::json body; if (!readJsonBody(req, res, body)) return; reply(res, service.validate(body)); }); server.Get("/health", [&service](const httplib::Request&, httplib::Response& res) { reply(res, service.health()); }); // An unexpected throw must not take the process down: one bad function // would otherwise stop every other tenant's. server.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) { std::string what = "unknown error"; try { std::rethrow_exception(ep); } catch (const std::exception& e) { what = e.what(); } catch (...) {} spdlog::error("unhandled exception on {} {}: {}", req.method, req.path, what); res.status = 500; res.set_content(nlohmann::json{{"ok", false}, {"error", what}}.dump(), "application/json"); }); // Bind BEFORE notifying, on this thread. listen() binds and serves in one // call, so notifying after merely spawning the thread would tell systemd we // are ready while the bind was still pending - or had already failed. Under // Type=notify that makes a runner that is about to exit look started, and // anything ordered after it would briefly see success. if (!server.bind_to_port(cfg.httpBind, cfg.httpPort)) { spdlog::critical("cannot bind {}:{} - address in use, or not permitted", cfg.httpBind, cfg.httpPort); return 1; } std::atomic serveFailed{false}; std::thread http([&] { if (!server.listen_after_bind()) { spdlog::error("the listener stopped unexpectedly"); serveFailed = true; g_running = false; } }); spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms http / {}ms job)", cfg.httpBind, cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs, cfg.maxJobWallTimeMs); // Only matters for a job-kind run REQUESTED OVER HTTP: the socket would be // cut before the runner could report its own timeout, and the caller would // read a 503 instead of a 504. Queue-claimed jobs are unaffected, which is // why this is a warning and not a refusal to start. if (cfg.maxJobWallTimeMs >= static_cast(cfg.readTimeoutSec) * 1000) { spdlog::warn("the job wall ceiling ({}ms) is at or above this server's read timeout" " ({}s); a job-kind run posted to /run would have its socket cut before" " it could report a timeout", cfg.maxJobWallTimeMs, cfg.readTimeoutSec); } sd_notify(0, "READY=1"); while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } sd_notify(0, "STOPPING=1"); server.stop(); if (http.joinable()) http.join(); // Non-zero on a listener failure, so Restart=on-failure actually fires. A // signal-driven shutdown is a clean exit. return serveFailed ? 1 : 0; }