Преглед изворни кода

feat(runner): QuickJS execution core with per-run limits and a runtime pool

The sandbox half of the function runtime: compile a script to bytecode,
run its default export in a fresh context under memory, wall-time and
stack ceilings, and pool the runtimes so a run does not pay for runtime
construction.

A fresh JSContext per run is NOT enough to isolate tenants, which the
design document got wrong. QuickJS keeps the microtask queue on the
JSRuntime, so a run that times out mid-microtask leaves jobs queued and
they would execute inside the next tenant's run. Leftovers are flushed
with the deadline forced into the past - each aborts at its first
bytecode op, so one spinning job cannot hang the flush - and if anything
survives the runtime is marked poisoned and the pool destroys it instead
of leasing it out. An OOM poisons it too.

OOM is corroborated rather than string-matched: QuickJS throws a bare
null when it cannot allocate even the Error object, so the classifier
also accepts an allocator sitting near the ceiling.

Recycling judges allocation AFTER a forced GC. A finished run leaves its
whole realm uncollected, so judging before would retire every runtime and
defeat the pool.

quickjs-ng pinned to an exact tag, not Bellard's tree: the module,
promise and stack entry points this needs are public API there. The exact
pin is load bearing - bytecode carries no version stamp, so an upgrade
makes a cached blob misread rather than fail. JsBytecode is documented as
an in-process cache only.

QuickJS stays behind a pimpl, so quickjs.h reaches no other translation
unit and vectorapi never links it.

BUILD_RUNNER is OFF by default: this vendors QuickJS over the network at
configure time, and neither an ordinary build nor the existing test cycle
may start depending on a GitHub fetch. The directory also builds as its
own top-level project, which is how it runs on the dev host - it links
neither vectorapi_core nor the database client, making it the one part of
this repo that compiles there.

30 tests, including both timeout paths, the leftover-jobs case, an
allocation storm, tenant isolation of globals and prototypes, a 660-run
leak check against QuickJS's own accounting, and pool concurrency.
fszontagh пре 1 месец
родитељ
комит
5ed2285446

+ 12 - 0
CMakeLists.txt

@@ -15,6 +15,12 @@ endif()
 
 option(BUILD_TESTS "Build tests" ON)
 option(BUILD_WEBUI "Build the React web UI via npm" ON)
+# The function runner vendors QuickJS over the network at configure time, so it
+# stays opt-in: an ordinary build and the whole existing test cycle must not
+# start depending on a GitHub fetch. Build it on its own with
+#   cmake -S runner -B build-runner
+# which also works on the dev host, where the root project cannot configure.
+option(BUILD_RUNNER "Build the QuickJS function runner" OFF)
 
 include(GNUInstallDirs)
 list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
@@ -49,6 +55,12 @@ if(BUILD_TESTS)
     add_subdirectory(tests)
 endif()
 
+# After the BUILD_TESTS block on purpose: runner/CMakeLists.txt registers tests,
+# which needs enable_testing() to have run already.
+if(BUILD_RUNNER)
+    add_subdirectory(runner)
+endif()
+
 if(BUILD_WEBUI)
     include(WebUI OPTIONAL)   # provided by plan 2; absent is fine
 endif()

+ 6 - 1
packaging/devstack/run-tests.sh

@@ -20,6 +20,9 @@ DB_DEB="${DB_DEB:-$DEB_REPO_DIR/dist/smartbotic-database_2.11.4-1_amd64.deb}"
 CLIENT_DEV_DEB="${CLIENT_DEV_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client-dev_2.11.4-1_amd64.deb}"
 CLIENT_DEB="${CLIENT_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client_2.11.4-1_amd64.deb}"
 FILTER="${1:-}"
+# BUILD_RUNNER=ON also builds and tests the QuickJS runner. Off by default
+# because it vendors QuickJS from GitHub at configure time.
+BUILD_RUNNER="${BUILD_RUNNER:-OFF}"
 
 docker image inspect "$BASE_IMAGE" >/dev/null 2>&1 || {
     echo "base image $BASE_IMAGE missing; build it with packaging/build.sh --rebuild-base" >&2
@@ -37,6 +40,7 @@ docker run --rm \
     -v "$CLIENT_DEB:/tmp/client.deb:ro" \
     -v "$CLIENT_DEV_DEB:/tmp/client-dev.deb:ro" \
     -e "CTEST_FILTER=$FILTER" \
+    -e "BUILD_RUNNER=$BUILD_RUNNER" \
     "$BASE_IMAGE" bash -euo pipefail -c '
         apt-get update -qq >/dev/null
         apt-get install -y -qq --no-install-recommends \
@@ -51,7 +55,8 @@ docker run --rm \
         (exec 3<>/dev/tcp/127.0.0.1/9004) 2>/dev/null || { echo "database never came up:"; tail -20 /tmp/db.log; exit 1; }
 
         cmake -B /build -G Ninja -DCMAKE_BUILD_TYPE=Release \
-              -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF -S /src
+              -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF \
+              -DBUILD_RUNNER="${BUILD_RUNNER}" -S /src
         cmake --build /build -j"$(nproc)"
         if [[ -n "${CTEST_FILTER:-}" ]]; then
             ctest --test-dir /build --output-on-failure -R "$CTEST_FILTER"

+ 98 - 0
runner/CMakeLists.txt

@@ -0,0 +1,98 @@
+# The function runner's execution core.
+#
+# This directory builds two ways: as a subdirectory of the root project, and as
+# a project of its own (`cmake -S runner -B build-runner`). The second is how it
+# gets built and tested on the dev host, where the root project cannot configure
+# at all because smartbotic-db-client is unbuildable there (see CLAUDE.md).
+if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
+    cmake_minimum_required(VERSION 3.20)
+    project(smartbotic-vectorapi-runner LANGUAGES C CXX)
+    set(CMAKE_CXX_STANDARD 20)
+    set(CMAKE_CXX_STANDARD_REQUIRED ON)
+    set(CMAKE_CXX_EXTENSIONS OFF)
+    if(NOT CMAKE_BUILD_TYPE)
+        set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type" FORCE)
+    endif()
+    option(BUILD_TESTS "Build tests" ON)
+    enable_testing()
+endif()
+
+# QuickJS is C, and the root project declares CXX only.
+enable_language(C)
+
+#
+# Deliberately self-contained: it links neither vectorapi_core nor
+# smartbotic-db-client, so it configures, builds and tests on the dev host whose
+# protobuf is too new for the database client (see CLAUDE.md gotchas). The
+# host-binding workstream that does need the gateway links THAT on top of this
+# target, it does not move the dependency in here.
+
+include(FetchContent)
+
+# quickjs-ng rather than Bellard's quickjs: it ships a real CMake build, exports
+# the module/promise/bytecode entry points we need as public API
+# (JS_GetModuleNamespace, JS_PromiseState, JS_SetMaxStackSize), builds clean
+# under a C++ TU's expectations, and is the variant that is actually maintained.
+# Pinned to an exact tag - bytecode has no version stamp, so a silent QuickJS
+# upgrade would make cached blobs misread.
+set(SVAPI_QUICKJS_TAG "v0.17.0" CACHE STRING "quickjs-ng git tag to vendor")
+
+set(QJS_ENABLE_INSTALL OFF CACHE BOOL "" FORCE)   # quickjs must not land in our .deb
+set(QJS_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
+set(QJS_BUILD_LIBC OFF CACHE BOOL "" FORCE)       # no std/os modules: slice 1 has no filesystem
+set(QJS_BUILD_CLI_WITH_MIMALLOC OFF CACHE BOOL "" FORCE)
+set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
+
+# quickjs-ng adds qjs/qjsc/api-test unconditionally; EXCLUDE_FROM_ALL keeps them
+# out of our default build. The guard is for CMake < 3.28, where the option does
+# not exist yet and the extra targets are merely wasted build time.
+if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28)
+    FetchContent_Declare(quickjs
+        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
+        GIT_TAG        ${SVAPI_QUICKJS_TAG}
+        GIT_SHALLOW    TRUE
+        EXCLUDE_FROM_ALL)
+else()
+    FetchContent_Declare(quickjs
+        GIT_REPOSITORY https://github.com/quickjs-ng/quickjs.git
+        GIT_TAG        ${SVAPI_QUICKJS_TAG}
+        GIT_SHALLOW    TRUE)
+endif()
+FetchContent_MakeAvailable(quickjs)
+
+# Found by the root project already; the guard is what makes this directory
+# usable on its own.
+if(NOT TARGET nlohmann_json::nlohmann_json)
+    find_package(nlohmann_json REQUIRED)
+endif()
+
+add_library(runner_core STATIC
+    src/js_runtime.cpp)
+target_include_directories(runner_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
+target_link_libraries(runner_core PUBLIC nlohmann_json::nlohmann_json PRIVATE qjs)
+target_compile_features(runner_core PUBLIC cxx_std_20)
+set_target_properties(runner_core PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+find_package(Threads REQUIRED)
+target_link_libraries(runner_core PUBLIC Threads::Threads)
+
+if(BUILD_TESTS)
+    # Same find-then-fetch dance as tests/CMakeLists.txt, guarded so that
+    # wiring this directory into the root project does not fetch twice.
+    if(NOT TARGET GTest::gtest_main)
+        find_package(GTest QUIET)
+        if(NOT GTest_FOUND)
+            message(STATUS "GTest not found on the system - fetching googletest")
+            FetchContent_Declare(googletest
+                GIT_REPOSITORY https://github.com/google/googletest.git
+                GIT_TAG        v1.15.2)
+            set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
+            FetchContent_MakeAvailable(googletest)
+        endif()
+    endif()
+    include(GoogleTest)
+
+    add_executable(test_js_runtime tests/js_runtime_test.cpp)
+    target_link_libraries(test_js_runtime PRIVATE runner_core GTest::gtest_main)
+    gtest_discover_tests(test_js_runtime PROPERTIES TIMEOUT 120)
+endif()

+ 205 - 0
runner/include/runner/js_runtime.hpp

@@ -0,0 +1,205 @@
+#pragma once
+#include <nlohmann/json.hpp>
+
+#include <condition_variable>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+/// QuickJS execution core for the function runner.
+///
+/// The contract is docs/superpowers/specs/2026-10-06-function-runtime-design.md
+/// ("Safety"): per-run memory, wall-time and stack limits, and a fresh
+/// `JSContext` per run so nothing leaks between tenants. QuickJS itself is kept
+/// behind a pimpl so no other translation unit in the runner has to see
+/// quickjs.h - and so vectorapi, which must not link QuickJS at all, could
+/// still include this header if it ever needed the types.
+namespace svapi::runner {
+
+/// Per-run ceilings. `wall_time_ms` is the configured maximum, not a default a
+/// descriptor can raise: run()'s override is clamped to it.
+struct JsLimits {
+    size_t memory_limit_bytes = 128u * 1024 * 1024;
+    int64_t wall_time_ms = 2000;
+    size_t max_stack_bytes = 512u * 1024;
+};
+
+/// A compiled module, serialised as QuickJS bytecode. The runner caches these
+/// by `content_hash`, so the representation has to be a plain byte blob.
+///
+/// The blob is only portable across processes running the SAME QuickJS build on
+/// the same architecture - QuickJS stamps no version into it and will happily
+/// misread a foreign blob. It is a cache, never a storage format: the registry
+/// keeps `source`.
+struct JsBytecode {
+    std::vector<uint8_t> bytes;
+    bool empty() const { return bytes.empty(); }
+};
+
+/// Outcome of one run. `timed_out` and `out_of_memory` are classified rather
+/// than folded into `error`, because the HTTP layer maps them to different
+/// statuses and an operator needs to tell a slow function from a broken one.
+struct JsResult {
+    bool ok = false;
+    nlohmann::json value;
+    std::string error;
+    std::vector<std::string> console_output;
+    bool timed_out = false;
+    bool out_of_memory = false;
+    int64_t duration_ms = 0;
+};
+
+/// Handles for a host-binding implementation, as opaque pointers so this header
+/// stays free of QuickJS types. `js_context` is a `JSContext*`; `ctx_object`
+/// points at the `JSValue` run() is about to pass to the default export, owned
+/// by run() and valid only for the duration of the install call.
+struct JsBindingTarget {
+    void* js_context = nullptr;
+    void* ctx_object = nullptr;
+};
+
+/// Extension point for the workstream that adds `ctx.collections`, `ctx.fetch`
+/// and `ctx.env`. It exists now only so run()'s signature does not have to
+/// change later; this file deliberately ships no implementation of it.
+class JsHostBindings {
+public:
+    virtual ~JsHostBindings() = default;
+
+    /// Decorate the ctx object for one run. Returning false with `error` set
+    /// fails the run before any user code executes.
+    virtual bool install(const JsBindingTarget& target, std::string& error) = 0;
+};
+
+/// One QuickJS runtime. Not thread-safe: QuickJS allows a runtime to be used
+/// from one thread at a time, which is what JsRuntimePool guarantees.
+class JsRuntime {
+public:
+    explicit JsRuntime(JsLimits limits = {});
+    ~JsRuntime();
+
+    JsRuntime(const JsRuntime&) = delete;
+    JsRuntime& operator=(const JsRuntime&) = delete;
+
+    /// Compile `source` as an ES module. `filename` only shows up in
+    /// diagnostics, so it should be whatever the operator will recognise.
+    std::optional<JsBytecode> compile(std::string_view source, const std::string& filename,
+                                      std::string& error_out);
+
+    /// Evaluate the module in a FRESH context and call its default export with
+    /// `ctx_arg`, awaiting the result. `wall_time_override_ms` > 0 narrows the
+    /// deadline and is clamped to `limits().wall_time_ms`.
+    JsResult run(const JsBytecode& bytecode, const nlohmann::json& ctx_arg,
+                 int64_t wall_time_override_ms = 0, JsHostBindings* host = nullptr);
+
+    /// Evaluate the module in a fresh context and read one named export WITHOUT
+    /// calling the default export. This is how a function's `on` descriptor is
+    /// read, so it must never execute the handler body. A declared-but-missing
+    /// export yields a null json, not an error.
+    std::optional<nlohmann::json> readExport(const JsBytecode& bytecode,
+                                             const std::string& export_name,
+                                             std::string& error_out);
+
+    /// Bytes currently held by the runtime's allocator, as QuickJS accounts
+    /// them. The pool uses this to decide whether to recycle.
+    size_t mallocBytes() const;
+
+    /// Force a full GC. The pool calls this before judging mallocBytes(),
+    /// because a finished run leaves its realm unreachable but not collected.
+    void collectGarbage();
+
+    /// Re-anchor QuickJS's stack-overflow detection to the calling thread.
+    /// A runtime records the stack top when it is created, so a pooled runtime
+    /// handed to a different thread would otherwise mis-measure the stack.
+    void updateStackTop();
+
+    /// True when this runtime must not serve another tenant: a run left
+    /// microtasks queued (the job queue lives on the runtime, not the context,
+    /// so a fresh context cannot clear it) or the allocator hit its limit.
+    bool poisoned() const;
+
+    const JsLimits& limits() const;
+
+private:
+    struct Impl;
+    std::unique_ptr<Impl> impl_;
+};
+
+/// Fixed-size pool of runtimes. Runtimes are pooled, contexts never are.
+class JsRuntimePool {
+public:
+    /// RAII lease. Holding one is what gives a thread exclusive use of a
+    /// runtime; dropping it hands the runtime back (or retires it).
+    class Lease {
+    public:
+        Lease() = default;
+        ~Lease();
+        Lease(Lease&& other) noexcept;
+        Lease& operator=(Lease&& other) noexcept;
+        Lease(const Lease&) = delete;
+        Lease& operator=(const Lease&) = delete;
+
+        JsRuntime& operator*() const { return *runtime_; }
+        JsRuntime* operator->() const { return runtime_; }
+        bool valid() const { return runtime_ != nullptr; }
+
+        /// Hand the runtime back early.
+        void release();
+
+    private:
+        friend class JsRuntimePool;
+        Lease(JsRuntimePool* pool, std::unique_ptr<JsRuntime> runtime);
+
+        JsRuntimePool* pool_ = nullptr;
+        JsRuntime* runtime_ = nullptr;
+        std::unique_ptr<JsRuntime> owned_;
+    };
+
+    /// `recycle_above_bytes` == 0 means half of `limits.memory_limit_bytes`:
+    /// a runtime still holding that much after a GC is discarded instead of
+    /// being handed on, so one greedy run cannot degrade every later tenant.
+    explicit JsRuntimePool(size_t size, JsLimits limits = {}, size_t recycle_above_bytes = 0);
+    ~JsRuntimePool();
+
+    JsRuntimePool(const JsRuntimePool&) = delete;
+    JsRuntimePool& operator=(const JsRuntimePool&) = delete;
+
+    /// Block until a runtime is free, then hand it out stack-top-corrected for
+    /// the calling thread.
+    Lease acquire();
+
+    /// Change the target size. Growing is immediate; shrinking only discards
+    /// idle runtimes - an in-use one is retired when its lease is dropped.
+    void resize(size_t size);
+
+    /// Target size, which after a shrink can be below the number of runtimes
+    /// still leased out.
+    size_t size() const;
+
+    /// Runtimes sitting idle right now. Diagnostics only: it can be stale the
+    /// instant it returns.
+    size_t idle() const;
+
+    /// Runtimes thrown away since construction - poisoned, over the allocation
+    /// watermark, or surplus after a shrink. Worth exporting as a metric: a
+    /// climbing count means functions are leaving memory pinned.
+    size_t retired() const;
+
+private:
+    void give_back(std::unique_ptr<JsRuntime> runtime);
+
+    mutable std::mutex mutex_;
+    std::condition_variable cv_;
+    std::vector<std::unique_ptr<JsRuntime>> idle_;
+    size_t live_ = 0;     // created runtimes: idle plus leased out
+    size_t target_ = 0;
+    size_t retired_ = 0;
+    JsLimits limits_;
+    size_t recycle_above_bytes_ = 0;
+};
+
+} // namespace svapi::runner

+ 688 - 0
runner/src/js_runtime.cpp

@@ -0,0 +1,688 @@
+#include "runner/js_runtime.hpp"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cstring>
+#include <stdexcept>
+#include <utility>
+
+#include "quickjs.h"
+
+namespace svapi::runner {
+namespace {
+
+int64_t nowMs() {
+    using namespace std::chrono;
+    return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
+}
+
+/// Console capture is bounded: a function in a loop could otherwise turn
+/// console.log into an unmetered allocation channel, and the run result travels
+/// over HTTP to whoever invoked it.
+constexpr size_t kMaxConsoleLines = 1000;
+constexpr size_t kMaxConsoleBytes = 64u * 1024;
+
+/// How many pending jobs a timed-out run may be flushed with before the runtime
+/// is declared poisoned. Flushing happens with the deadline already expired, so
+/// each job is interrupted at its first bytecode op; the cap only bounds a
+/// module that keeps re-enqueueing from that interrupted frame.
+constexpr int kPoisonFlushBudget = 256;
+
+/// Per-run state, hung off the context. One context per run means this is
+/// created and destroyed with the run, which is exactly the lifetime we want.
+struct RunState {
+    std::vector<std::string> console;
+    size_t console_bytes = 0;
+    bool console_truncated = false;
+
+    void add(std::string line) {
+        if (console.size() >= kMaxConsoleLines || console_bytes >= kMaxConsoleBytes) {
+            if (!console_truncated) {
+                console_truncated = true;
+                console.emplace_back("[console output truncated]");
+            }
+            return;
+        }
+        console_bytes += line.size();
+        console.push_back(std::move(line));
+    }
+};
+
+/// Shared with the interrupt handler, which QuickJS may call from inside any JS
+/// frame - including one running under JS_ExecutePendingJob.
+struct RuntimeState {
+    std::atomic<int64_t> deadline_ms{0};  // 0 = no run in progress, no deadline
+    std::atomic<bool> interrupted{false};
+};
+
+int interruptHandler(JSRuntime*, void* opaque) {
+    auto* state = static_cast<RuntimeState*>(opaque);
+    const int64_t deadline = state->deadline_ms.load(std::memory_order_relaxed);
+    if (deadline == 0 || nowMs() < deadline) return 0;
+    state->interrupted.store(true, std::memory_order_relaxed);
+    return 1;  // unwinds the whole JS stack with an uncatchable-ish InternalError
+}
+
+std::string toText(JSContext* ctx, JSValueConst v) {
+    const char* s = JS_ToCString(ctx, v);
+    if (!s) {
+        JS_FreeValue(ctx, JS_GetException(ctx));  // stringification itself can throw
+        return "<unprintable>";
+    }
+    std::string out(s);
+    JS_FreeCString(ctx, s);
+    return out;
+}
+
+/// Format a thrown value the way an operator wants to read it: the message
+/// first, then the stack if QuickJS attached one.
+std::string formatThrown(JSContext* ctx, JSValue exc) {
+    std::string text;
+    if (JS_IsNull(exc) || JS_IsUndefined(exc)) {
+        // QuickJS throws a bare null when it could not even allocate the Error
+        // object, which in practice only happens under the memory limit.
+        text = "out of memory";
+    } else {
+        text = toText(ctx, exc);
+        if (JS_IsObject(exc)) {
+            JSValue stack = JS_GetPropertyStr(ctx, exc, "stack");
+            if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {
+                std::string st = toText(ctx, stack);
+                if (!st.empty()) text += "\n" + st;
+            }
+            JS_FreeValue(ctx, stack);
+        }
+    }
+    JS_FreeValue(ctx, exc);
+    return text;
+}
+
+std::string takeException(JSContext* ctx) { return formatThrown(ctx, JS_GetException(ctx)); }
+
+/// Values cross the boundary as JSON, which is also the only shape the registry
+/// and the HTTP protocol can carry. Non-serialisable values (functions,
+/// undefined) come back as null rather than failing the run.
+bool fromJs(JSContext* ctx, JSValueConst v, nlohmann::json& out, std::string& error) {
+    JSValue json = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
+    if (JS_IsException(json)) {
+        error = takeException(ctx);
+        JS_FreeValue(ctx, json);
+        return false;
+    }
+    if (JS_IsUndefined(json)) {  // undefined, a function, a symbol
+        JS_FreeValue(ctx, json);
+        out = nullptr;
+        return true;
+    }
+    const std::string text = toText(ctx, json);
+    JS_FreeValue(ctx, json);
+    out = nlohmann::json::parse(text, nullptr, false);
+    if (out.is_discarded()) {
+        error = "the returned value is not representable as JSON";
+        return false;
+    }
+    return true;
+}
+
+JSValue toJs(JSContext* ctx, const nlohmann::json& j) {
+    const std::string text = j.dump();
+    return JS_ParseJSON(ctx, text.c_str(), text.size(), "<ctx>");
+}
+
+/// console.log/warn/error. The level travels as a prefix because the protocol
+/// carries one flat `console[]` array and a timeout diagnosis usually hinges on
+/// whether the last line was an error.
+JSValue consoleWrite(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int magic) {
+    auto* state = static_cast<RunState*>(JS_GetContextOpaque(ctx));
+    if (!state) return JS_UNDEFINED;
+
+    std::string line;
+    if (magic == 1) line = "[warn] ";
+    if (magic == 2) line = "[error] ";
+    for (int i = 0; i < argc; i++) {
+        if (i > 0) line += ' ';
+        // Objects as JSON, primitives as text: "[object Object]" in a log is
+        // worse than useless when debugging a function.
+        if (JS_IsObject(argv[i]) && !JS_IsFunction(ctx, argv[i])) {
+            JSValue json = JS_JSONStringify(ctx, argv[i], JS_UNDEFINED, JS_UNDEFINED);
+            if (!JS_IsException(json) && !JS_IsUndefined(json)) {
+                line += toText(ctx, json);
+                JS_FreeValue(ctx, json);
+                continue;
+            }
+            if (JS_IsException(json)) JS_FreeValue(ctx, JS_GetException(ctx));
+            JS_FreeValue(ctx, json);
+        }
+        line += toText(ctx, argv[i]);
+    }
+    state->add(std::move(line));
+    return JS_UNDEFINED;
+}
+
+void installConsole(JSContext* ctx) {
+    JSValue global = JS_GetGlobalObject(ctx);
+    JSValue console = JS_NewObject(ctx);
+    JS_SetPropertyStr(ctx, console, "log",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "log", 1, JS_CFUNC_generic_magic, 0));
+    JS_SetPropertyStr(ctx, console, "info",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "info", 1, JS_CFUNC_generic_magic, 0));
+    JS_SetPropertyStr(ctx, console, "debug",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "debug", 1, JS_CFUNC_generic_magic, 0));
+    JS_SetPropertyStr(ctx, console, "warn",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "warn", 1, JS_CFUNC_generic_magic, 1));
+    JS_SetPropertyStr(ctx, console, "error",
+                      JS_NewCFunctionMagic(ctx, consoleWrite, "error", 1, JS_CFUNC_generic_magic, 2));
+    JS_SetPropertyStr(ctx, global, "console", console);
+    JS_FreeValue(ctx, global);
+}
+
+} // namespace
+
+struct JsRuntime::Impl {
+    JSRuntime* rt = nullptr;
+    JsLimits limits;
+    RuntimeState state;
+    bool poisoned = false;
+
+    /// Fresh context for one run or one descriptor read. Nothing a tenant can
+    /// reach survives this object, which is the whole point.
+    JSContext* newContext(RunState* run_state) {
+        JSContext* ctx = JS_NewContext(rt);
+        if (!ctx) return nullptr;
+        JS_SetContextOpaque(ctx, run_state);
+        installConsole(ctx);
+        return ctx;
+    }
+
+    void armDeadline(int64_t budget_ms) {
+        state.interrupted.store(false, std::memory_order_relaxed);
+        state.deadline_ms.store(nowMs() + budget_ms, std::memory_order_relaxed);
+    }
+
+    void disarmDeadline() { state.deadline_ms.store(0, std::memory_order_relaxed); }
+
+    bool expired() const {
+        const int64_t deadline = state.deadline_ms.load(std::memory_order_relaxed);
+        return deadline != 0 && nowMs() >= deadline;
+    }
+
+    bool interrupted() const { return state.interrupted.load(std::memory_order_relaxed); }
+
+    size_t mallocBytes() const {
+        JSMemoryUsage usage{};
+        JS_ComputeMemoryUsage(rt, &usage);
+        return static_cast<size_t>(usage.malloc_size);
+    }
+
+    /// An allocation failure may surface either as an InternalError carrying
+    /// "out of memory" or, when even that Error could not be allocated, as a
+    /// bare null. Neither is reliable on its own, so corroborate with the
+    /// allocator: close to the ceiling, an error is a memory error.
+    bool looksLikeOom(const std::string& error) const {
+        if (error.find("out of memory") != std::string::npos) return true;
+        return nearMemoryCeiling();
+    }
+
+    bool nearMemoryCeiling() const {
+        if (limits.memory_limit_bytes == 0) return false;
+        return mallocBytes() >= limits.memory_limit_bytes / 10 * 9;
+    }
+
+    /// Run queued microtasks until the queue drains or the deadline passes.
+    /// The C++ clock check only stops the LOOP; what stops a single job that
+    /// never returns is the interrupt handler firing inside it.
+    void drainJobs(std::string& job_error) {
+        while (JS_IsJobPending(rt)) {
+            if (expired() || interrupted()) return;
+            JSContext* job_ctx = nullptr;
+            const int rc = JS_ExecutePendingJob(rt, &job_ctx);
+            if (rc == 0) return;
+            if (rc < 0 && job_ctx && job_error.empty()) job_error = takeException(job_ctx);
+        }
+    }
+
+    /// Resolve `value` to a settled, non-promise value, draining microtasks as
+    /// needed. Consumes `value`.
+    JSValue await(JSContext* ctx, JSValue value, std::string& error) {
+        for (;;) {
+            std::string job_error;
+            drainJobs(job_error);
+
+            const JSPromiseStateEnum st = JS_PromiseState(ctx, value);
+            if (st == JS_PROMISE_NOT_A_PROMISE) {
+                if (!job_error.empty() && error.empty()) error = job_error;
+                return value;
+            }
+            if (st == JS_PROMISE_FULFILLED) {
+                JSValue inner = JS_PromiseResult(ctx, value);
+                JS_FreeValue(ctx, value);
+                value = inner;  // a promise resolving to a promise must be followed
+                continue;
+            }
+            if (st == JS_PROMISE_REJECTED) {
+                JS_PromiseMarkAsHandled(ctx, value);
+                JSValue reason = JS_PromiseResult(ctx, value);
+                JS_FreeValue(ctx, value);
+                error = formatThrown(ctx, reason);
+                return JS_UNDEFINED;
+            }
+            // Still pending with nothing left to run: either we ran out of time
+            // or the function returned a promise nobody will ever settle.
+            JS_PromiseMarkAsHandled(ctx, value);
+            JS_FreeValue(ctx, value);
+            if (error.empty()) {
+                error = interrupted() || expired()
+                            ? "wall-time limit exceeded"
+                            : (job_error.empty() ? "the returned promise never settled" : job_error);
+            }
+            return JS_UNDEFINED;
+        }
+    }
+
+    /// Instantiate and evaluate module bytecode in `ctx`. Returns the module
+    /// definition, or nullptr with `error` set.
+    JSModuleDef* evaluateModule(JSContext* ctx, const JsBytecode& bytecode, std::string& error) {
+        JSValue obj = JS_ReadObject(ctx, bytecode.bytes.data(), bytecode.bytes.size(),
+                                    JS_READ_OBJ_BYTECODE);
+        if (JS_IsException(obj)) {
+            error = takeException(ctx);
+            JS_FreeValue(ctx, obj);
+            return nullptr;
+        }
+        if (!JS_IsModule(obj)) {
+            JS_FreeValue(ctx, obj);
+            error = "the compiled artifact is not an ES module";
+            return nullptr;
+        }
+        if (JS_ResolveModule(ctx, obj) < 0) {
+            error = takeException(ctx);
+            JS_FreeValue(ctx, obj);
+            return nullptr;
+        }
+        auto* module = static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(obj));
+
+        // JS_EvalFunction consumes obj and, because a module may top-level
+        // await, hands back a promise rather than a finished evaluation.
+        JSValue eval_result = JS_EvalFunction(ctx, obj);
+        if (JS_IsException(eval_result)) {
+            error = takeException(ctx);
+            JS_FreeValue(ctx, eval_result);
+            return nullptr;
+        }
+        JS_FreeValue(ctx, await(ctx, eval_result, error));
+        if (!error.empty()) return nullptr;
+        return module;
+    }
+
+    /// After a timed-out run the job queue still holds this tenant's
+    /// microtasks, and that queue belongs to the RUNTIME, not the context a
+    /// fresh run would get. Try to flush it with the deadline still expired;
+    /// if anything survives, the runtime can never be reused.
+    void settleAfterRun() {
+        if (!JS_IsJobPending(rt)) return;
+        // Flush with the deadline forced into the past, so the interrupt
+        // handler aborts every leftover job at its first bytecode op. Without
+        // this a single leftover job spinning in a loop would hang the flush.
+        state.deadline_ms.store(nowMs() - 1, std::memory_order_relaxed);
+        for (int i = 0; i < kPoisonFlushBudget && JS_IsJobPending(rt); i++) {
+            JSContext* job_ctx = nullptr;
+            if (JS_ExecutePendingJob(rt, &job_ctx) < 0 && job_ctx) {
+                JS_FreeValue(job_ctx, JS_GetException(job_ctx));
+            }
+        }
+        if (JS_IsJobPending(rt)) poisoned = true;
+        disarmDeadline();
+    }
+};
+
+JsRuntime::JsRuntime(JsLimits limits) : impl_(std::make_unique<Impl>()) {
+    impl_->limits = limits;
+    impl_->rt = JS_NewRuntime();
+    if (!impl_->rt) throw std::runtime_error("JS_NewRuntime failed");
+    JS_SetMemoryLimit(impl_->rt, limits.memory_limit_bytes);
+    JS_SetMaxStackSize(impl_->rt, limits.max_stack_bytes);
+    JS_SetInterruptHandler(impl_->rt, interruptHandler, &impl_->state);
+}
+
+JsRuntime::~JsRuntime() {
+    if (impl_ && impl_->rt) {
+        // JS_FreeRuntime is the only call that clears leftover jobs, which is
+        // why a poisoned runtime is destroyed rather than cleaned up.
+        impl_->disarmDeadline();
+        JS_FreeRuntime(impl_->rt);
+    }
+}
+
+const JsLimits& JsRuntime::limits() const { return impl_->limits; }
+
+size_t JsRuntime::mallocBytes() const { return impl_->mallocBytes(); }
+
+void JsRuntime::updateStackTop() { JS_UpdateStackTop(impl_->rt); }
+
+void JsRuntime::collectGarbage() { JS_RunGC(impl_->rt); }
+
+bool JsRuntime::poisoned() const { return impl_->poisoned; }
+
+std::optional<JsBytecode> JsRuntime::compile(std::string_view source, const std::string& filename,
+                                             std::string& error_out) {
+    RunState run_state;
+    JSContext* ctx = impl_->newContext(&run_state);
+    if (!ctx) {
+        error_out = "out of memory";
+        return std::nullopt;
+    }
+
+    // Compiling arbitrary source is itself unbounded work (a pathological
+    // regexp or a huge literal), so it runs under the same wall-time ceiling.
+    impl_->armDeadline(impl_->limits.wall_time_ms);
+
+    std::optional<JsBytecode> result;
+    // JS_Eval requires a NUL-terminated buffer, which a string_view is not.
+    const std::string src(source);
+    JSValue obj = JS_Eval(ctx, src.c_str(), src.size(), filename.c_str(),
+                          JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
+    if (JS_IsException(obj)) {
+        error_out = takeException(ctx);
+    } else {
+        size_t size = 0;
+        uint8_t* buf = JS_WriteObject(ctx, &size, obj, JS_WRITE_OBJ_BYTECODE);
+        if (!buf) {
+            error_out = takeException(ctx);
+        } else {
+            JsBytecode bc;
+            bc.bytes.assign(buf, buf + size);
+            js_free(ctx, buf);
+            result = std::move(bc);
+        }
+    }
+    JS_FreeValue(ctx, obj);
+
+    impl_->disarmDeadline();
+    JS_FreeContext(ctx);
+    if (!result && error_out.empty()) error_out = "compilation failed";
+    return result;
+}
+
+JsResult JsRuntime::run(const JsBytecode& bytecode, const nlohmann::json& ctx_arg,
+                        int64_t wall_time_override_ms, JsHostBindings* host) {
+    JsResult result;
+    const auto started = std::chrono::steady_clock::now();
+    const auto finish = [&] {
+        result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
+                                 std::chrono::steady_clock::now() - started)
+                                 .count();
+        return result;
+    };
+
+    if (bytecode.empty()) {
+        result.error = "no compiled function to run";
+        return finish();
+    }
+    if (impl_->poisoned) {
+        result.error = "this runtime was retired and must not run another function";
+        return finish();
+    }
+
+    // A descriptor may ask for less time than the ceiling, never more.
+    int64_t budget = impl_->limits.wall_time_ms;
+    if (wall_time_override_ms > 0) budget = std::min(budget, wall_time_override_ms);
+
+    RunState run_state;
+    JSContext* ctx = impl_->newContext(&run_state);
+    if (!ctx) {
+        result.error = "out of memory";
+        result.out_of_memory = true;
+        impl_->poisoned = true;
+        return finish();
+    }
+
+    impl_->armDeadline(budget);
+
+    std::string error;
+    if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
+        JSValue ns = JS_GetModuleNamespace(ctx, module);
+        if (JS_IsException(ns)) {
+            error = takeException(ctx);
+        } else {
+            JSValue fn = JS_GetPropertyStr(ctx, ns, "default");
+            if (JS_IsException(fn)) {
+                error = takeException(ctx);
+            } else if (!JS_IsFunction(ctx, fn)) {
+                error = "the module has no default export function";
+            } else {
+                JSValue arg = toJs(ctx, ctx_arg);
+                if (JS_IsException(arg)) {
+                    error = takeException(ctx);
+                } else {
+                    if (host) {
+                        // install() decorates this object in place; it may not
+                        // swap the handle, which run() owns.
+                        JsBindingTarget target;
+                        target.js_context = ctx;
+                        target.ctx_object = &arg;
+                        std::string host_error;
+                        if (!host->install(target, host_error)) {
+                            error = host_error.empty() ? "host bindings failed to install"
+                                                       : host_error;
+                        }
+                    }
+                    if (error.empty()) {
+                        JSValue returned = JS_Call(ctx, fn, JS_UNDEFINED, 1, &arg);
+                        if (JS_IsException(returned)) {
+                            error = takeException(ctx);
+                            JS_FreeValue(ctx, returned);
+                        } else {
+                            JSValue settled = impl_->await(ctx, returned, error);
+                            if (error.empty()) fromJs(ctx, settled, result.value, error);
+                            JS_FreeValue(ctx, settled);
+                        }
+                    }
+                }
+                JS_FreeValue(ctx, arg);
+            }
+            JS_FreeValue(ctx, fn);
+        }
+        JS_FreeValue(ctx, ns);
+    }
+
+    // The handler fires inside a JS frame; the clock catches the case where the
+    // deadline passed between two microtasks, with no frame to interrupt.
+    const bool out_of_time = impl_->interrupted() || impl_->expired();
+    impl_->disarmDeadline();
+
+    result.console_output = std::move(run_state.console);
+    if (error.empty()) {
+        result.ok = true;
+    } else {
+        result.error = error;
+        if (out_of_time) {
+            result.timed_out = true;
+            result.error = "wall-time limit of " + std::to_string(budget) + " ms exceeded";
+        } else if (impl_->looksLikeOom(error)) {
+            result.out_of_memory = true;
+            // The allocator is at its ceiling with this tenant's data still
+            // reachable; hand this runtime back to nobody.
+            impl_->poisoned = true;
+        }
+    }
+
+    impl_->settleAfterRun();
+    JS_FreeContext(ctx);
+    return finish();
+}
+
+std::optional<nlohmann::json> JsRuntime::readExport(const JsBytecode& bytecode,
+                                                    const std::string& export_name,
+                                                    std::string& error_out) {
+    if (bytecode.empty()) {
+        error_out = "no compiled function to read";
+        return std::nullopt;
+    }
+    if (impl_->poisoned) {
+        error_out = "this runtime was retired";
+        return std::nullopt;
+    }
+
+    RunState run_state;
+    JSContext* ctx = impl_->newContext(&run_state);
+    if (!ctx) {
+        error_out = "out of memory";
+        return std::nullopt;
+    }
+
+    // Module evaluation runs top-level code, so it needs the same ceiling as a
+    // run. The default export is never called: reading a descriptor must not
+    // have side effects.
+    impl_->armDeadline(impl_->limits.wall_time_ms);
+
+    std::optional<nlohmann::json> result;
+    std::string error;
+    if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
+        JSValue ns = JS_GetModuleNamespace(ctx, module);
+        if (JS_IsException(ns)) {
+            error = takeException(ctx);
+        } else {
+            JSValue value = JS_GetPropertyStr(ctx, ns, export_name.c_str());
+            if (JS_IsException(value)) {
+                error = takeException(ctx);
+            } else {
+                nlohmann::json parsed;
+                if (fromJs(ctx, value, parsed, error)) result = std::move(parsed);
+            }
+            JS_FreeValue(ctx, value);
+        }
+        JS_FreeValue(ctx, ns);
+    }
+
+    const bool out_of_time = impl_->interrupted() || impl_->expired();
+    impl_->disarmDeadline();
+    if (!result) {
+        error_out = out_of_time ? "wall-time limit exceeded while loading the module"
+                                : (error.empty() ? "could not read export '" + export_name + "'"
+                                                 : error);
+        if (!out_of_time && impl_->looksLikeOom(error)) impl_->poisoned = true;
+    }
+
+    impl_->settleAfterRun();
+    JS_FreeContext(ctx);
+    return result;
+}
+
+// ---------------------------------------------------------------------------
+// Pool
+// ---------------------------------------------------------------------------
+
+JsRuntimePool::Lease::Lease(JsRuntimePool* pool, std::unique_ptr<JsRuntime> runtime)
+    : pool_(pool), runtime_(runtime.get()), owned_(std::move(runtime)) {}
+
+JsRuntimePool::Lease::Lease(Lease&& other) noexcept
+    : pool_(other.pool_), runtime_(other.runtime_), owned_(std::move(other.owned_)) {
+    other.pool_ = nullptr;
+    other.runtime_ = nullptr;
+}
+
+JsRuntimePool::Lease& JsRuntimePool::Lease::operator=(Lease&& other) noexcept {
+    if (this != &other) {
+        release();
+        pool_ = other.pool_;
+        runtime_ = other.runtime_;
+        owned_ = std::move(other.owned_);
+        other.pool_ = nullptr;
+        other.runtime_ = nullptr;
+    }
+    return *this;
+}
+
+JsRuntimePool::Lease::~Lease() { release(); }
+
+void JsRuntimePool::Lease::release() {
+    if (pool_ && owned_) pool_->give_back(std::move(owned_));
+    pool_ = nullptr;
+    runtime_ = nullptr;
+    owned_.reset();
+}
+
+JsRuntimePool::JsRuntimePool(size_t size, JsLimits limits, size_t recycle_above_bytes)
+    : target_(size), limits_(limits), recycle_above_bytes_(recycle_above_bytes) {
+    if (recycle_above_bytes_ == 0) recycle_above_bytes_ = limits_.memory_limit_bytes / 2;
+}
+
+JsRuntimePool::~JsRuntimePool() = default;
+
+size_t JsRuntimePool::size() const {
+    std::lock_guard<std::mutex> lock(mutex_);
+    return target_;
+}
+
+size_t JsRuntimePool::idle() const {
+    std::lock_guard<std::mutex> lock(mutex_);
+    return idle_.size();
+}
+
+size_t JsRuntimePool::retired() const {
+    std::lock_guard<std::mutex> lock(mutex_);
+    return retired_;
+}
+
+JsRuntimePool::Lease JsRuntimePool::acquire() {
+    std::unique_lock<std::mutex> lock(mutex_);
+    cv_.wait(lock, [this] { return !idle_.empty() || live_ < target_; });
+
+    std::unique_ptr<JsRuntime> runtime;
+    if (!idle_.empty()) {
+        runtime = std::move(idle_.back());
+        idle_.pop_back();
+    } else {
+        // Runtimes are created on demand, so a pool sized for peak load costs
+        // nothing until that load arrives.
+        runtime = std::make_unique<JsRuntime>(limits_);
+        live_++;
+    }
+    lock.unlock();
+
+    // QuickJS measures stack depth against the stack top it recorded at
+    // creation; a pooled runtime almost always runs on a different thread.
+    runtime->updateStackTop();
+    return Lease(this, std::move(runtime));
+}
+
+void JsRuntimePool::give_back(std::unique_ptr<JsRuntime> runtime) {
+    // Decide outside the lock: a GC on a bloated runtime can take a while, and
+    // nothing else may touch this runtime while its lease is being dropped.
+    bool retire = runtime->poisoned();
+    if (!retire && runtime->mallocBytes() > recycle_above_bytes_) {
+        // Only the figure AFTER a full GC means anything. A finished run
+        // normally leaves its whole realm unreachable but not yet collected,
+        // and dropping a perfectly good runtime over that would defeat pooling.
+        runtime->collectGarbage();
+        retire = runtime->mallocBytes() > recycle_above_bytes_;
+    }
+
+    std::lock_guard<std::mutex> lock(mutex_);
+    if (!retire && live_ > target_) retire = true;  // the pool shrank while this was out
+    if (retire) {
+        runtime.reset();
+        live_--;
+        retired_++;
+    } else {
+        idle_.push_back(std::move(runtime));
+    }
+    cv_.notify_one();
+}
+
+void JsRuntimePool::resize(size_t size) {
+    std::lock_guard<std::mutex> lock(mutex_);
+    target_ = size;
+    // Only idle runtimes can go now; a leased one is retired by give_back,
+    // because destroying a runtime another thread is executing in would take
+    // the process down with it.
+    while (live_ > target_ && !idle_.empty()) {
+        idle_.pop_back();
+        live_--;
+        retired_++;
+    }
+    cv_.notify_all();
+}
+
+} // namespace svapi::runner

+ 507 - 0
runner/tests/js_runtime_test.cpp

@@ -0,0 +1,507 @@
+// Tests for the QuickJS execution core. These are the executable form of the
+// safety contract in docs/superpowers/specs/2026-10-06-function-runtime-design.md
+// ("Safety"): per-run limits, a fresh context per run, nothing leaking between
+// tenants. They must stay runnable on the dev host, so nothing here touches the
+// database client.
+#include <gtest/gtest.h>
+
+#include <atomic>
+#include <chrono>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "runner/js_runtime.hpp"
+
+using svapi::runner::JsBytecode;
+using svapi::runner::JsLimits;
+using svapi::runner::JsResult;
+using svapi::runner::JsRuntime;
+using svapi::runner::JsRuntimePool;
+
+namespace {
+
+JsBytecode compileOk(JsRuntime& rt, const std::string& src) {
+    std::string error;
+    auto bc = rt.compile(src, "test.js", error);
+    EXPECT_TRUE(bc.has_value()) << "compile failed: " << error;
+    if (!bc) return JsBytecode{};
+    EXPECT_FALSE(bc->empty());
+    return *bc;
+}
+
+} // namespace
+
+TEST(JsRuntime, ReturnsTheDefaultExportsValue) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function (ctx) { return { hi: ctx.name, n: 2 + 3 }; }");
+
+    JsResult r = rt.run(bc, nlohmann::json{{"name", "world"}});
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value.at("hi"), "world");
+    EXPECT_EQ(r.value.at("n"), 5);
+    EXPECT_FALSE(r.timed_out);
+    EXPECT_FALSE(r.out_of_memory);
+}
+
+TEST(JsRuntime, AwaitsAnAsyncDefaultExport) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export default async function (ctx) {"
+                        "  const v = await Promise.resolve(ctx.a + ctx.b);"
+                        "  return { sum: v };"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json{{"a", 20}, {"b", 22}});
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value.at("sum"), 42);
+}
+
+TEST(JsRuntime, ReportsASyntaxErrorCleanly) {
+    JsRuntime rt;
+    std::string error;
+    auto bc = rt.compile("export default function ( { return", "broken.js", error);
+    EXPECT_FALSE(bc.has_value());
+    EXPECT_NE(error.find("SyntaxError"), std::string::npos) << error;
+    // The filename must survive into the diagnostic, otherwise an operator
+    // cannot tell which function failed to load.
+    EXPECT_NE(error.find("broken.js"), std::string::npos) << error;
+}
+
+TEST(JsRuntime, ReportsAThrownErrorWithoutClaimingSuccess) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function () { throw new TypeError('nope'); }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("nope"), std::string::npos) << r.error;
+    EXPECT_FALSE(r.timed_out);
+}
+
+TEST(JsRuntime, ReportsARejectedPromise) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default async function () { throw new Error('async boom'); }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("async boom"), std::string::npos) << r.error;
+}
+
+TEST(JsRuntime, MissingDefaultExportIsAnError) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export const on = { id: 'x' };");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("default export"), std::string::npos) << r.error;
+}
+
+TEST(JsRuntime, InfiniteLoopHitsTheWallTimeLimit) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt, "export default function () { for (;;) {} }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.timed_out) << r.error;
+    EXPECT_LT(r.duration_ms, 5000);
+}
+
+// A module that keeps re-enqueueing microtasks never returns to the C++ loop,
+// so only the interrupt handler firing inside JS_ExecutePendingJob can stop it.
+TEST(JsRuntime, EndlessMicrotaskChainHitsTheWallTimeLimit) {
+    JsLimits limits;
+    limits.wall_time_ms = 200;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  const spin = () => Promise.resolve().then(spin);"
+                        "  spin();"
+                        "  return new Promise(() => {});"
+                        "}");
+
+    auto started = std::chrono::steady_clock::now();
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                       std::chrono::steady_clock::now() - started)
+                       .count();
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.timed_out) << r.error;
+    EXPECT_LT(elapsed, 5000);
+}
+
+// A timed-out run can leave queued jobs that each spin forever. Flushing them
+// must stay bounded, or the wall-time limit would be defeated by whatever runs
+// after the deadline rather than before it.
+TEST(JsRuntime, LeftoverSpinningJobsDoNotHangAfterTheDeadline) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  for (let i = 0; i < 50; i++) { Promise.resolve().then(() => { for (;;) {} }); }"
+                        "  return new Promise(() => {});"
+                        "}");
+
+    auto started = std::chrono::steady_clock::now();
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                       std::chrono::steady_clock::now() - started)
+                       .count();
+    EXPECT_TRUE(r.timed_out) << r.error;
+    EXPECT_LT(elapsed, 5000);
+}
+
+TEST(JsRuntime, AWallTimeOverrideIsClampedToTheConfiguredMaximum) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt, "export default function () { for (;;) {} }");
+
+    // A descriptor asking for 60s may not escape the configured ceiling.
+    JsResult r = rt.run(bc, nlohmann::json::object(), 60000);
+    EXPECT_TRUE(r.timed_out);
+    EXPECT_LT(r.duration_ms, 5000);
+}
+
+TEST(JsRuntime, AllocationStormHitsTheMemoryLimit) {
+    JsLimits limits;
+    limits.memory_limit_bytes = 8u * 1024 * 1024;
+    limits.wall_time_ms = 10000;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  const keep = [];"
+                        "  for (let i = 0; i < 1000000; i++) { keep.push(new Array(256).fill(i)); }"
+                        "  return keep.length;"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.out_of_memory) << r.error;
+    EXPECT_FALSE(r.timed_out) << r.error;
+}
+
+TEST(JsRuntime, CapturesConsoleOutput) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  console.log('hello', 1, { a: 2 });"
+                        "  console.warn('careful');"
+                        "  console.error('bad');"
+                        "  return true;"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    ASSERT_EQ(r.console_output.size(), 3u);
+    EXPECT_NE(r.console_output[0].find("hello 1"), std::string::npos) << r.console_output[0];
+    EXPECT_NE(r.console_output[0].find("\"a\":2"), std::string::npos) << r.console_output[0];
+    EXPECT_NE(r.console_output[1].find("careful"), std::string::npos) << r.console_output[1];
+    EXPECT_NE(r.console_output[2].find("bad"), std::string::npos) << r.console_output[2];
+}
+
+TEST(JsRuntime, ConsoleOutputFromATimedOutRunIsStillReturned) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto bc = compileOk(rt, "export default function () { console.log('before the hang'); for (;;) {} }");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    EXPECT_TRUE(r.timed_out);
+    ASSERT_EQ(r.console_output.size(), 1u);
+    EXPECT_NE(r.console_output[0].find("before the hang"), std::string::npos);
+}
+
+TEST(JsRuntime, ReadExportReturnsTheOnDescriptor) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic',"
+                        "                    method: 'GET' };\n"
+                        "export default function () { throw new Error('must not run'); }");
+
+    std::string error;
+    auto on = rt.readExport(bc, "on", error);
+    ASSERT_TRUE(on.has_value()) << error;
+    EXPECT_EQ(on->at("id"), "kb-search");
+    EXPECT_EQ(on->at("type"), "http");
+    EXPECT_EQ(on->at("route"), "/kb/:topic");
+    EXPECT_EQ(on->at("method"), "GET");
+}
+
+TEST(JsRuntime, ReadExportOfAMissingNameIsNull) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function () { return 1; }");
+
+    std::string error;
+    auto on = rt.readExport(bc, "on", error);
+    ASSERT_TRUE(on.has_value()) << error;
+    EXPECT_TRUE(on->is_null());
+}
+
+TEST(JsRuntime, ReadExportReportsAModuleThatThrowsAtTopLevel) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "throw new Error('top level boom');\nexport const on = {};");
+
+    std::string error;
+    auto on = rt.readExport(bc, "on", error);
+    EXPECT_FALSE(on.has_value());
+    EXPECT_NE(error.find("top level boom"), std::string::npos) << error;
+}
+
+// The tenant-isolation requirement: one run may never see another run's globals.
+TEST(JsRuntime, GlobalsDoNotLeakBetweenRuns) {
+    JsRuntime rt;
+    auto writer = compileOk(rt, "export default function () { globalThis.leaked = 'tenant-a'; return 1; }");
+    auto reader = compileOk(rt, "export default function () { return typeof globalThis.leaked; }");
+
+    JsResult first = rt.run(writer, nlohmann::json::object());
+    ASSERT_TRUE(first.ok) << first.error;
+
+    JsResult second = rt.run(reader, nlohmann::json::object());
+    ASSERT_TRUE(second.ok) << second.error;
+    EXPECT_EQ(second.value, "undefined");
+}
+
+TEST(JsRuntime, PrototypePollutionDoesNotLeakBetweenRuns) {
+    JsRuntime rt;
+    auto poison = compileOk(rt, "export default function () { Object.prototype.pwned = 7; return 1; }");
+    auto probe = compileOk(rt, "export default function () { return ({}).pwned === undefined; }");
+
+    ASSERT_TRUE(rt.run(poison, nlohmann::json::object()).ok);
+    JsResult r = rt.run(probe, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, true);
+}
+
+TEST(JsRuntime, SameBytecodeRunsRepeatedly) {
+    JsRuntime rt;
+    auto bc = compileOk(rt, "export default function (ctx) { return ctx.i * 2; }");
+    for (int i = 0; i < 5; i++) {
+        JsResult r = rt.run(bc, nlohmann::json{{"i", i}});
+        ASSERT_TRUE(r.ok) << r.error;
+        EXPECT_EQ(r.value, i * 2);
+    }
+}
+
+TEST(JsRuntime, RunsAgainAfterATimeout) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntime rt(limits);
+    auto hang = compileOk(rt, "export default function () { for (;;) {} }");
+    auto fine = compileOk(rt, "export default function () { return 'alive'; }");
+
+    EXPECT_TRUE(rt.run(hang, nlohmann::json::object()).timed_out);
+    JsResult r = rt.run(fine, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, "alive");
+}
+
+TEST(JsRuntime, NoHostGlobalsAreExposed) {
+    JsRuntime rt;
+    // Slice 1 has no filesystem, no storage and no egress: a script must not
+    // find a way out through a leftover global.
+    auto bc = compileOk(rt,
+                        "export default function () {"
+                        "  return ['std', 'os', 'require', 'fetch', 'XMLHttpRequest', 'process']"
+                        "      .filter((n) => typeof globalThis[n] !== 'undefined');"
+                        "}");
+
+    JsResult r = rt.run(bc, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_TRUE(r.value.empty()) << r.value.dump();
+}
+
+// QuickJS accounts every allocation it makes, so a JSValue this code forgets to
+// free shows up as a runtime whose footprint climbs run after run. That is the
+// only leak detector available on the dev host (no sanitizer runtimes), so it
+// is worth a test of its own.
+TEST(JsRuntime, RepeatedRunsDoNotLeakRuntimeMemory) {
+    JsRuntime rt;
+    auto bc = compileOk(rt,
+                        "export const on = { id: 'leaky' };\n"
+                        "export default async function (ctx) {"
+                        "  console.log('iteration', ctx.i);"
+                        "  const o = await Promise.resolve({ list: [1, 2, 3], s: 'x'.repeat(100) });"
+                        "  return o;"
+                        "}");
+    auto thrower = compileOk(rt, "export default function () { throw new Error('every time'); }");
+
+    const auto cycle = [&](int i) {
+        ASSERT_TRUE(rt.run(bc, nlohmann::json{{"i", i}}).ok);
+        ASSERT_FALSE(rt.run(thrower, nlohmann::json::object()).ok);
+        std::string error;
+        ASSERT_TRUE(rt.readExport(bc, "on", error).has_value()) << error;
+    };
+
+    for (int i = 0; i < 20; i++) cycle(i);
+    rt.collectGarbage();
+    const size_t baseline = rt.mallocBytes();
+
+    for (int i = 0; i < 200; i++) cycle(i);
+    rt.collectGarbage();
+    const size_t after = rt.mallocBytes();
+
+    // Some slack for the atom table, which grows but never shrinks; a real leak
+    // here is linear in the iteration count and blows straight past it.
+    EXPECT_LT(after, baseline + 256u * 1024)
+        << "baseline " << baseline << " grew to " << after << " over 200 runs";
+}
+
+TEST(JsRuntime, MallocBytesIsReported) {
+    JsRuntime rt;
+    EXPECT_GT(rt.mallocBytes(), 0u);
+}
+
+TEST(JsRuntimePool, ServesConcurrentThreadsSafely) {
+    JsRuntimePool pool(4);
+    JsRuntime compiler;
+    auto bc = compileOk(compiler, "export default function (ctx) { return ctx.n + 1; }");
+
+    std::atomic<int> ok{0};
+    std::atomic<int> failed{0};
+    std::vector<std::thread> threads;
+    for (int t = 0; t < 16; t++) {
+        threads.emplace_back([&pool, &bc, &ok, &failed, t] {
+            for (int i = 0; i < 10; i++) {
+                auto lease = pool.acquire();
+                JsResult r = lease->run(bc, nlohmann::json{{"n", t}});
+                if (r.ok && r.value == t + 1) {
+                    ok++;
+                } else {
+                    failed++;
+                }
+            }
+        });
+    }
+    for (auto& th : threads) th.join();
+    EXPECT_EQ(failed.load(), 0);
+    EXPECT_EQ(ok.load(), 160);
+}
+
+TEST(JsRuntimePool, AcquireBlocksUntilARuntimeIsFree) {
+    JsRuntimePool pool(1);
+    std::atomic<bool> second_got_it{false};
+
+    auto lease = pool.acquire();
+    std::thread waiter([&pool, &second_got_it] {
+        auto l = pool.acquire();
+        second_got_it = true;
+    });
+
+    std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    EXPECT_FALSE(second_got_it.load()) << "the single runtime was handed out twice";
+
+    lease.release();
+    waiter.join();
+    EXPECT_TRUE(second_got_it.load());
+}
+
+TEST(JsRuntimePool, ResizeDoesNotDestroyAnInUseRuntime) {
+    JsRuntimePool pool(3);
+    JsRuntime compiler;
+    auto bc = compileOk(compiler, "export default function () { return 'still here'; }");
+
+    auto lease = pool.acquire();
+    pool.resize(1);
+    EXPECT_EQ(pool.size(), 1u);
+
+    // The lease stays valid even though the pool shrank below the number of
+    // runtimes that were handed out.
+    JsResult r = lease->run(bc, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, "still here");
+
+    lease.release();
+    EXPECT_LE(pool.size(), 1u);
+}
+
+TEST(JsRuntimePool, ResizeUpAllowsMoreConcurrentLeases) {
+    JsRuntimePool pool(1);
+    auto first = pool.acquire();
+    pool.resize(2);
+    auto second = pool.acquire();   // would block forever at size 1
+    EXPECT_TRUE(second.valid());
+}
+
+TEST(JsRuntimePool, RecyclesARuntimeWhoseAllocationStaysHigh) {
+    JsLimits limits;
+    limits.memory_limit_bytes = 64u * 1024 * 1024;
+    // A watermark below a bare runtime's own footprint, so "still over the
+    // watermark after a GC" is guaranteed and the retirement path is what the
+    // test observes - not QuickJS's reclamation behaviour on a given version.
+    JsRuntimePool pool(1, limits, 1024);
+    JsRuntime compiler;
+    auto bc = compileOk(compiler, "export default function () { return 1; }");
+
+    {
+        auto lease = pool.acquire();
+        ASSERT_TRUE(lease->run(bc, nlohmann::json::object()).ok);
+        EXPECT_GT(lease->mallocBytes(), 1024u);
+    }
+    EXPECT_EQ(pool.retired(), 1u) << "a runtime over the watermark was kept";
+
+    // Retiring must not shrink the pool: the next tenant still gets served.
+    auto lease = pool.acquire();
+    ASSERT_TRUE(lease.valid());
+    EXPECT_EQ(pool.size(), 1u);
+    EXPECT_TRUE(lease->run(bc, nlohmann::json::object()).ok);
+}
+
+// The other half of the rule: a run whose memory a GC reclaims must NOT cost a
+// runtime, or pooling buys nothing under normal load.
+TEST(JsRuntimePool, KeepsARuntimeWhoseMemoryTheGcReclaims) {
+    JsLimits limits;
+    limits.memory_limit_bytes = 64u * 1024 * 1024;
+    JsRuntimePool pool(1, limits, 1024 * 1024);
+    JsRuntime compiler;
+    auto bloat = compileOk(compiler,
+                           "export default function () {"
+                           "  globalThis.keep = [];"
+                           "  for (let i = 0; i < 20000; i++) { globalThis.keep.push(new Array(64).fill(i)); }"
+                           "  return globalThis.keep.length;"
+                           "}");
+
+    size_t peak = 0;
+    {
+        auto lease = pool.acquire();
+        JsResult r = lease->run(bloat, nlohmann::json::object());
+        ASSERT_TRUE(r.ok) << r.error;
+        peak = lease->mallocBytes();
+    }
+    EXPECT_GT(peak, 1024u * 1024) << "the bloat run did not actually allocate";
+    EXPECT_EQ(pool.retired(), 0u);
+
+    auto lease = pool.acquire();
+    EXPECT_LT(lease->mallocBytes(), 1024u * 1024) << "the runtime was handed on still bloated";
+}
+
+TEST(JsRuntimePool, RetiresARuntimeLeftWithPendingJobs) {
+    JsLimits limits;
+    limits.wall_time_ms = 150;
+    JsRuntimePool pool(1, limits);
+    JsRuntime compiler;
+    auto spin = compileOk(compiler,
+                          "export default function () {"
+                          "  const again = () => Promise.resolve().then(again);"
+                          "  again();"
+                          "  return new Promise(() => {});"
+                          "}");
+    auto probe = compileOk(compiler, "export default function () { return 'clean'; }");
+
+    {
+        auto lease = pool.acquire();
+        JsResult r = lease->run(spin, nlohmann::json::object());
+        EXPECT_TRUE(r.timed_out) << r.error;
+        // Unexecuted microtasks live on the runtime, not the context, so this
+        // runtime can never be handed to another tenant.
+        EXPECT_TRUE(lease->poisoned());
+    }
+
+    auto lease = pool.acquire();
+    EXPECT_FALSE(lease->poisoned());
+    JsResult r = lease->run(probe, nlohmann::json::object());
+    ASSERT_TRUE(r.ok) << r.error;
+    EXPECT_EQ(r.value, "clean");
+}