Ver Fonte

feat(functions): CRUD endpoints, HTTP dispatch and the runner client

The server half. Functions are managed under
/api/v1/projects/{p}/functions and served to the world at /fn/{project}/*.

Code and capability stay split, as the design requires: a push goes
through FunctionRegistry::put(), which preserves server-held policy, and
a policy change is a separate ADMIN-only route. A write is validated on a
runner before storage - the engine that validates is the engine that will
execute - and with no healthy runner the write is refused with 503 rather
than stored unchecked. The id comes from the script's `on` block, never
from the URL.

RunnerPool's retry rule is the spine of runner_client.cpp and splits
three ways, not two. Never connected: retry, nothing can have run.
Answered, whatever the answer: never retry, the runner did its job.
Delivered then unanswered - a read timeout, a non-200, an unparseable
body: do NOT retry and mark unhealthy, because the handler may be running
right now and a retry would run a side-effecting function twice with
nothing in the logs saying so. A read timeout is the trap: the failure
most tempting to retry and the one that most reliably double-executes.
validate() retries everything, because compiling a script has no side
effects.

/fn/* is unauthenticated, so the project is the first path segment and is
treated as hostile input: charset-restricted (excluding `:`, the
separator qualify() is built on), confirmed against listProjects() before
anything qualifies a collection, and `..` refused anywhere in the
remainder - httplib percent-decodes before we see the path, and while
`..` cannot match a literal pattern segment it CAN be captured by a
:name param and used as a key downstream.

Disabled and invalid functions are absent from the descriptor list, so
they 404 rather than 403: a public caller learns nothing about what a
project holds. Function error text stays out of the response for the same
reason - a JS stack trace on an open endpoint is an information leak - and
goes to the run log, which the project's own people read through
GET .../functions/{id}/logs. The response carries the run_id so they can
find it.

Rows are sorted by function_id before route matching: matchHttpRoute
resolves ties by declaration order and the database promises nothing
about list() order, so without this two functions sharing a route could
swap across a restart.

404 and 405 stay distinct, with Allow: on the 405. The SPA history
fallback had to learn about /fn/: it rewrites any extensionless 404 to
index.html, so a request for a function that does not exist would have
returned the web UI with status 200.

The run log is trimmed on write, bounded to 64 deletes per append. There
is no scheduler to prune it yet, and an unbounded log on a busy function
fills the database quietly.

api/openapi.json and api/llms.txt document all of it.

399/399 tests pass in the Debian 13 container with BUILD_RUNNER=ON.
fszontagh há 1 mês atrás
pai
commit
35522f28c9

+ 3 - 0
CMakeLists.txt

@@ -68,6 +68,9 @@ endif()
 # Install: config conffile, api docs
 install(FILES ${CMAKE_SOURCE_DIR}/config/config.json
     DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/smartbotic-vectorapi)
+install(FILES ${CMAKE_SOURCE_DIR}/runner/config/runner.json
+    DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}/smartbotic-vectorapi
+    OPTIONAL)
 install(FILES ${CMAKE_SOURCE_DIR}/api/openapi.json
               ${CMAKE_SOURCE_DIR}/api/llms.txt
     DESTINATION ${CMAKE_INSTALL_DATADIR}/smartbotic-vectorapi

+ 20 - 0
api/llms.txt

@@ -143,6 +143,26 @@ Precedence for one embedding call: the collection's own `embedding_model` wins,
 - `PUT  /api/v1/projects/{project}/settings/embeddings` `{openai_api_base?, openai_api_key?, default_embedding_model?}` - Omit a field to leave it unchanged; send `null` to clear the override and inherit the global value. An empty string is rejected with **422**. Setting `openai_api_base` without an `openai_api_key` for the same project is rejected with **422** `embedding_base_requires_key`, so the global credential is never sent to a foreign endpoint. A project key without a project base URL is allowed (own key, default endpoint).
 - `DELETE /api/v1/projects/{project}/settings/embeddings` - Drop every override; the project inherits the global settings again.
 
+## Functions
+
+Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.
+
+**The id lives in the source, not in the URL.** A script exports `export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }`, and that `id` is the registry row's identity. `path` records where the author keeps the file and carries no meaning, so moving `kb-search.js` to `lib/search.js` keeps the same row - and the policy an admin granted travels with it.
+
+**Every write is compiled on a runner before it is stored.** The engine that validates is the engine that will execute. A compile failure is **422** `compile_failed` with the error; an `on` block with no id is **422** `missing_function_id`; no healthy runner is **503** `no_runner` and nothing is stored. Code is never stored unvalidated.
+
+**A code push can never widen access.** `policy` is server state: a `policy` field sent with a `POST`/`PUT` body is ignored (not merged, not consulted as a fallback), and `enabled` is likewise preserved, so re-pushing code does not re-enable a function an operator turned off. A first registration inherits the project's default policy, which currently grants **no collection at all** - the function runs, logs and can call out, but reaches no data until an admin grants it a rule.
+
+- `GET  /api/v1/projects/{project}/functions` - List functions **without their sources**: `{functions:[{function_id, path, content_hash, descriptor, policy, enabled, valid, last_error, created_at, updated_at}]}`.
+- `POST /api/v1/projects/{project}/functions` `{source, path?}` - Register a new function; the id comes from the validated `on` block, so there is no `function_id` field to send. An id already in use is **409** `function_exists` (PUT it to update).
+- `GET  /api/v1/projects/{project}/functions/{id}` - Get one function, **including** `source`.
+- `PUT  /api/v1/projects/{project}/functions/{id}` `{source, path?}` - Push code. The id the script declares must equal the id in the URL; a mismatch is **422** `id_mismatch` (with `error.details.declared` and `error.details.url`) rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (**201**).
+- `DELETE /api/v1/projects/{project}/functions/{id}` - Delete the function, its code and its policy.
+- `PUT  /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
+- `PUT  /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
+- `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
+- `GET  /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, started_at}]}`. `?limit=` defaults to 50. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
+
 ## Stats
 
 - `GET /api/v1/projects/{project}/stats` - Per-project stats (collections, document counts). Accessible to any key granted the project.

+ 518 - 0
api/openapi.json

@@ -14,6 +14,93 @@
       }
     },
     "schemas": {
+      "FunctionDescriptor": {
+        "type": "object",
+        "description": "The validated `on` block the script exports. Server-held: it is whatever the runner parsed out of the source, never sent by a client.",
+        "properties": {
+          "id": { "type": "string", "description": "The function's identity, declared in the source. The file path is incidental, so a rename carries the policy with it." },
+          "type": { "type": "string", "enum": ["http", "cron", "db"], "description": "Only `http` is dispatched in this release; the others parse so a newer script gets a clear message rather than being treated as a route." },
+          "route": { "type": "string", "description": "HTTP trigger: the path pattern, with `:name` segments captured into ctx.params" },
+          "method": { "type": "array", "items": { "type": "string" }, "description": "HTTP trigger: accepted methods, upper-cased. ABSENT means every method, not none." },
+          "schedule": { "type": "string", "description": "Cron trigger: validated for shape only; nothing schedules it yet" },
+          "table": { "type": "string", "description": "Database trigger: the collection watched" },
+          "event": { "type": "string", "enum": ["INSERT", "UPDATE", "DELETE"] },
+          "timeoutMs": { "type": "integer", "description": "Declared wall-clock budget. Omitted when the script did not declare one; a declared value is still clamped to the runner's configured maximum." },
+          "singleFlight": { "type": "boolean" }
+        },
+        "required": ["id", "type"]
+      },
+      "FunctionPolicy": {
+        "type": "object",
+        "description": "What a function may touch, in exactly the vocabulary API keys use - a function is a principal, not a key holder. Policy is SERVER state: it is set only by an admin through PUT .../functions/{id}/policy, and a `policy` field sent with a code push is ignored. An empty or absent rule set grants no collection at all, which is what a first registration inherits.",
+        "properties": {
+          "rules": {
+            "type": "array",
+            "items": { "$ref": "#/components/schemas/KeyScopeRule" },
+            "description": "A function reaches a collection only if a matching rule exists for the (collection, op) pair. Unlike a key scope, an empty array is legal: it is the deny-everything default."
+          },
+          "origins": { "type": "array", "items": { "type": "string" }, "description": "Unused for functions; carried because the policy shares the key-scope shape" },
+          "rate_limit_per_min": { "type": "integer", "minimum": 0, "description": "Maximum runs per minute. 0 means unlimited." },
+          "expires_at": { "type": "integer", "description": "Unix epoch seconds after which the policy is treated as expired. 0 means never." }
+        }
+      },
+      "FunctionSummary": {
+        "type": "object",
+        "description": "A registry row without its source. Listings return this shape so one response does not ship every function's whole body.",
+        "properties": {
+          "function_id": { "type": "string", "description": "Declared in the script's `on` block. Called `function_id`, not `id`, because the database client strips a top-level `id` from stored bodies." },
+          "path": { "type": "string", "description": "Where the author keeps the file. Carries no meaning: changing it keeps the same row, and the policy with it." },
+          "content_hash": { "type": "string", "description": "sha256 of the source, lower-case hex. The runner caches compiled bytecode by this." },
+          "descriptor": { "$ref": "#/components/schemas/FunctionDescriptor" },
+          "policy": { "$ref": "#/components/schemas/FunctionPolicy" },
+          "enabled": { "type": "boolean", "description": "Server state: re-pushing code never re-enables a function an operator turned off" },
+          "valid": { "type": "boolean" },
+          "last_error": { "type": "string" },
+          "created_at": { "type": "integer" },
+          "updated_at": { "type": "integer" }
+        },
+        "required": ["function_id", "descriptor", "policy", "enabled", "valid"]
+      },
+      "Function": {
+        "allOf": [
+          { "$ref": "#/components/schemas/FunctionSummary" },
+          {
+            "type": "object",
+            "properties": { "source": { "type": "string", "description": "The JavaScript as stored. Returned by the single-function GET only." } }
+          }
+        ]
+      },
+      "FunctionRun": {
+        "type": "object",
+        "description": "One recorded run. The log is append-only and trimmed to the newest N runs per function on every write, so an old run_id eventually stops resolving.",
+        "properties": {
+          "run_id": { "type": "string" },
+          "function_id": { "type": "string" },
+          "trigger": { "type": "string", "enum": ["http", "invoke"], "description": "`http` for a dispatched request, `invoke` for a manual POST .../invoke" },
+          "ok": { "type": "boolean" },
+          "status": { "type": "integer" },
+          "duration_ms": { "type": "integer" },
+          "error": { "type": "string" },
+          "console": { "type": "array", "items": { "type": "string" } },
+          "started_at": { "type": "integer", "description": "Unix epoch seconds" }
+        }
+      },
+      "FunctionRunResult": {
+        "type": "object",
+        "description": "What one run produced. The HTTP status of the invoke call reports whether the run could be PERFORMED; this envelope reports what the function did.",
+        "properties": {
+          "run_id": { "type": "string", "description": "Also the id of the run-log entry this invoke appended" },
+          "ok": { "type": "boolean" },
+          "status": { "type": "integer", "description": "The status the function returned" },
+          "headers": { "type": "object", "additionalProperties": { "type": "string" } },
+          "body": { "description": "Whatever the function returned; any JSON type, including null" },
+          "console": { "type": "array", "items": { "type": "string" } },
+          "duration_ms": { "type": "integer" },
+          "error": { "type": "string" },
+          "timed_out": { "type": "boolean" },
+          "out_of_memory": { "type": "boolean" }
+        }
+      },
       "ProjectEmbeddingSettings": {
         "type": "object",
         "description": "Three views of a project's embedding configuration. In overrides, an empty string means the field is inherited.",
@@ -1530,6 +1617,437 @@
         }
       }
     },
+    "/api/v1/projects/{project}/functions": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        }
+      ],
+      "get": {
+        "summary": "List this project's functions, without their sources",
+        "operationId": "listFunctions",
+        "responses": {
+          "200": {
+            "description": "Function list",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "functions": { "type": "array", "items": { "$ref": "#/components/schemas/FunctionSummary" } }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" }
+        }
+      },
+      "post": {
+        "summary": "Register a new function. The source is compiled on a runner BEFORE it is stored, and its id comes from the script's `on` block - not from this request.",
+        "description": "The id is read from the validated descriptor, so there is no `function_id` field to send. A `policy` field is ignored: policy is server state, changed only by an admin through PUT .../functions/{id}/policy. A first registration inherits the project's default policy, which currently grants no collection at all.",
+        "operationId": "createFunction",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "source": { "type": "string", "description": "The JavaScript module. Must export an `on` object declaring at least an id." },
+                  "path": { "type": "string", "description": "Where the author keeps the file. Stored as-is and never used as an identity." }
+                },
+                "required": ["source"]
+              }
+            }
+          }
+        },
+        "responses": {
+          "201": {
+            "description": "Function stored",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "409": {
+            "description": "A function with this id already exists (code function_exists) - PUT it to update",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "422": {
+            "description": "The source did not compile (code compile_failed), the `on` block declares no id (code missing_function_id), or `source` is missing (code validation)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "503": {
+            "description": "No healthy runner to validate against (code no_runner / runner_unreachable). Code is never stored unvalidated.",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "get": {
+        "summary": "Get one function, including its source",
+        "operationId": "getFunction",
+        "responses": {
+          "200": {
+            "description": "The function",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Function" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" }
+        }
+      },
+      "put": {
+        "summary": "Push code to this function. Validated on a runner first, and the stored policy and enabled flag are preserved - a code push can never widen access.",
+        "description": "The id in the URL must equal the id the script declares; a mismatch is 422 rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (201).",
+        "operationId": "updateFunction",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "source": { "type": "string" },
+                  "path": { "type": "string" }
+                },
+                "required": ["source"]
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Function updated",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "201": {
+            "description": "Function registered (the id was unused)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "422": {
+            "description": "The source did not compile (code compile_failed), declares no id (code missing_function_id), or declares an id other than the one in the URL (code id_mismatch, with details.declared and details.url)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "503": {
+            "description": "No healthy runner to validate against (code no_runner / runner_unreachable)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      },
+      "delete": {
+        "summary": "Delete a function, its code and its policy",
+        "operationId": "deleteFunction",
+        "responses": {
+          "200": {
+            "description": "Deleted",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": { "deleted": { "type": "string" } }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/policy": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "put": {
+        "summary": "Replace what this function may touch (ADMIN ONLY). The only route that changes a policy.",
+        "description": "Developers push code, admins grant access - the same split API keys already have, which is why this route is admin-only while the rest of the function routes are not. An empty rule set is accepted and means the function reaches no collection.",
+        "operationId": "setFunctionPolicy",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "description": "Either {\"policy\": {...}} or the policy object itself.",
+                "properties": { "policy": { "$ref": "#/components/schemas/FunctionPolicy" } }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Policy replaced",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionSummary" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires an admin key" },
+          "404": { "description": "No such function" },
+          "422": {
+            "description": "Malformed policy: a rule without a collection or ops, or an unknown op (code validation)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/enabled": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "put": {
+        "summary": "Enable or disable a function. Server state: a later code push does not re-enable it.",
+        "operationId": "setFunctionEnabled",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": { "enabled": { "type": "boolean" } },
+                "required": ["enabled"]
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Updated",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "function_id": { "type": "string" },
+                    "enabled": { "type": "boolean" }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" },
+          "422": { "description": "`enabled` missing or not a boolean (code validation)" }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/invoke": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "post": {
+        "summary": "Run a function once with a synthesised trigger, and record the run",
+        "description": "Every field of the body is optional: an empty body invokes the function with its own route as the path and POST as the method. The call answers 200 whenever the run was PERFORMED, even if the function itself failed - its status, error and console output are in the envelope. The run is appended to the function's log either way.",
+        "operationId": "invokeFunction",
+        "requestBody": {
+          "required": false,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "properties": {
+                  "method": { "type": "string", "description": "Defaults to POST" },
+                  "path": { "type": "string", "description": "Defaults to the route the descriptor declares" },
+                  "params": { "type": "object", "description": "ctx.params - what a real route match would have captured", "additionalProperties": { "type": "string" } },
+                  "query": { "type": "object", "description": "ctx.query", "additionalProperties": { "type": "string" } },
+                  "headers": { "type": "object", "additionalProperties": { "type": "string" } },
+                  "body": { "description": "ctx.body; any JSON type" }
+                }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "The run was performed; the envelope says what the function did",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/FunctionRunResult" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" },
+          "409": {
+            "description": "The function is disabled (code function_disabled) or marked invalid (code function_invalid)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          },
+          "503": {
+            "description": "No healthy runner (code no_runner), or no runner could be reached for this run (code runner_unreachable, with details.run_id - the failed attempt is still logged)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/functions/{id}/logs": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "The function id declared in the script's `on` block"
+        }
+      ],
+      "get": {
+        "summary": "This function's recorded runs, newest first",
+        "description": "The log keeps only the newest N runs per function (trimmed on every write), so a limit above N returns N.",
+        "operationId": "listFunctionRuns",
+        "parameters": [
+          {
+            "name": "limit",
+            "in": "query",
+            "required": false,
+            "schema": { "type": "integer", "minimum": 1 },
+            "description": "Maximum runs to return; defaults to 50 and is clamped to how many the server keeps"
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "Run log",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "function_id": { "type": "string" },
+                    "runs": { "type": "array", "items": { "$ref": "#/components/schemas/FunctionRun" } }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such function" },
+          "422": { "description": "`limit` is not a positive integer (code validation)" }
+        }
+      }
+    },
     "/api/v1/settings": {
       "get": {
         "summary": "Get current settings (admin only); openai_api_key is masked to a boolean openai_api_key_set",

+ 5 - 0
src/CMakeLists.txt

@@ -4,6 +4,7 @@ add_library(vectorapi_core STATIC
     db_errors.cpp
     json_http.cpp
     filters.cpp
+    vector_search.cpp
     db_gateway.cpp
     settings.cpp
     project_settings.cpp
@@ -15,6 +16,8 @@ add_library(vectorapi_core STATIC
     collection_registry.cpp
     function_record.cpp
     function_registry.cpp
+    function_run_log.cpp
+    runner_client.cpp
     embeddings.cpp
     embedding_cache.cpp
     rate_limiter.cpp
@@ -33,6 +36,8 @@ add_library(vectorapi_core STATIC
     handlers/settings.cpp
     handlers/project_settings.cpp
     handlers/relations.cpp
+    handlers/functions.cpp
+    handlers/function_dispatch.cpp
     functions/descriptor.cpp
     functions/net_guard.cpp
 )

+ 12 - 0
src/config.cpp

@@ -15,6 +15,18 @@ Config Config::fromJson(const nlohmann::json& j) {
     if (j.contains("database") && j["database"].is_object()) {
         c.dbAddress = j["database"].value("address", c.dbAddress);
     }
+    if (j.contains("functions") && j["functions"].is_object()) {
+        const auto& f = j["functions"];
+        if (f.contains("runners") && f["runners"].is_array()) {
+            // Bind before iterating: a range-for over a temporary subobject of a
+            // parsed document dangles (see CLAUDE.md).
+            const nlohmann::json& runners = f["runners"];
+            for (const auto& e : runners)
+                if (e.is_string() && !e.get<std::string>().empty())
+                    c.runnerEndpoints.push_back(e.get<std::string>());
+        }
+        c.functionRunsKept = f.value("runs_kept", c.functionRunsKept);
+    }
     return c;
 }
 

+ 12 - 0
src/config.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include <cstdint>
 #include <string>
+#include <vector>
 #include <nlohmann/json.hpp>
 
 namespace svapi {
@@ -12,6 +13,17 @@ struct Config {
     std::string dbAddress = "localhost:9004";
     std::string webuiDir  = "/usr/share/smartbotic-vectorapi/webui";
 
+    /// Function runner endpoints ("host:port"). Empty disables the function
+    /// routes outright: with nowhere to validate a script, storing one would
+    /// mean storing unchecked code.
+    ///
+    /// A static list on purpose - dynamic registration is only worth its
+    /// failure modes once autoscaling exists.
+    std::vector<std::string> runnerEndpoints;
+    /// Runs kept per function. There is no scheduler to prune them yet, so the
+    /// log is trimmed on write; unbounded, a busy function fills the database.
+    uint32_t functionRunsKept = 50;
+
     static Config fromJson(const nlohmann::json& j);
     static Config load(const std::string& path);  // reads file then fromJson
 };

+ 104 - 0
src/function_run_log.cpp

@@ -0,0 +1,104 @@
+#include "function_run_log.hpp"
+
+namespace svapi {
+namespace {
+
+/// One trim pass deletes at most this many rows. The pass runs on every append,
+/// so a backlog - `keepPerFunction` lowered from 1000 to 10, or rows written by
+/// an older build - drains over the following appends instead of turning one
+/// invocation into a thousand deletes.
+constexpr uint32_t kMaxTrimPerAppend = 64;
+
+/// Rows of one function, newest first. `started_at` is the sort key because it
+/// is the only ordering the caller controls; two runs inside the same second
+/// are therefore ordered arbitrarily, which only decides which of two equally
+/// old rows is dropped first.
+smartbotic::database::Client::QueryOptions newestFirst(const std::string& functionId,
+                                                       uint32_t offset, uint32_t limit) {
+    smartbotic::database::Client::QueryOptions opts;
+    opts.filters.push_back(smartbotic::database::Client::Filter::eq("function_id", functionId));
+    opts.sortField = "started_at";
+    opts.sortDescending = true;
+    opts.offset = offset;
+    opts.limit = limit;
+    return opts;
+}
+
+/// Drop everything past the newest `keep` runs of one function.
+///
+/// Deletes by the body's `run_id`, not by a returned `id`: the client strips a
+/// top-level `id` from stored bodies, so the document id has to be carried in
+/// the body to be readable again (the same reason API keys store `key_id`).
+void trimOldest(smartbotic::database::Client& c, const std::string& collection,
+                const std::string& functionId, uint32_t keep) {
+    if (keep == 0) return;  // 0 = keep everything, as elsewhere in this codebase
+    for (const auto& doc : c.find(collection, newestFirst(functionId, keep, kMaxTrimPerAppend))) {
+        const std::string runId = doc.value("run_id", std::string());
+        if (!runId.empty()) c.remove(collection, runId);
+    }
+}
+
+}  // namespace
+
+FunctionRunLog FunctionRunLog::fromJson(const nlohmann::json& j) {
+    FunctionRunLog e;
+    e.runId      = j.value("run_id", "");
+    e.functionId = j.value("function_id", "");
+    e.trigger    = j.value("trigger", "");
+    e.ok         = j.value("ok", false);
+    e.status     = j.value("status", 0);
+    e.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
+    e.error      = j.value("error", "");
+    if (j.contains("console") && j.at("console").is_array()) {
+        const nlohmann::json& lines = j.at("console");
+        for (const auto& line : lines)
+            if (line.is_string()) e.console.push_back(line.get<std::string>());
+    }
+    e.startedAt = j.value("started_at", 0ull);
+    return e;
+}
+
+nlohmann::json FunctionRunLog::toJson() const {
+    // `run_id`, never `id` - see trimOldest above.
+    return {{"run_id", runId},
+            {"function_id", functionId},
+            {"trigger", trigger},
+            {"ok", ok},
+            {"status", status},
+            {"duration_ms", durationMs},
+            {"error", error},
+            {"console", console},
+            {"started_at", startedAt}};
+}
+
+FunctionRunLogStore::FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction)
+    : db_(db), keep_(keepPerFunction) {}
+
+void FunctionRunLogStore::ensure(const std::string& project) {
+    const std::string c = coll(project);
+    if (!db_.client().getCollectionInfo(c).has_value())
+        db_.client().createCollection(c, 0, false, 0, 0);
+}
+
+void FunctionRunLogStore::append(const std::string& project, const FunctionRunLog& entry) {
+    ensure(project);
+    db_.client().upsert(coll(project), entry.toJson(), entry.runId);
+    // Trimmed here rather than by a background job: there is no scheduler yet,
+    // and a busy function would otherwise fill the database unnoticed.
+    trimOldest(db_.client(), coll(project), entry.functionId, keep_);
+}
+
+std::vector<FunctionRunLog> FunctionRunLogStore::list(const std::string& project,
+                                                      const std::string& functionId,
+                                                      uint32_t limit) {
+    // A caller asking for more than is kept cannot get more than is kept, so
+    // clamping here keeps a huge ?limit= from becoming a huge query.
+    if (limit == 0) limit = 50;
+    if (keep_ != 0 && limit > keep_) limit = keep_;
+    std::vector<FunctionRunLog> out;
+    for (const auto& doc : db_.client().find(coll(project), newestFirst(functionId, 0, limit)))
+        out.push_back(FunctionRunLog::fromJson(doc));
+    return out;
+}
+
+}  // namespace svapi

+ 47 - 0
src/function_run_log.hpp

@@ -0,0 +1,47 @@
+#pragma once
+#include "db_gateway.hpp"
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// One recorded run. Kept deliberately small: a run log is written on every
+/// invocation, so anything stored here is stored thousands of times.
+struct FunctionRunLog {
+    std::string runId;
+    std::string functionId;
+    std::string trigger;      // "http" | "invoke"
+    bool ok = false;
+    int status = 0;
+    int64_t durationMs = 0;
+    std::string error;
+    std::vector<std::string> console;
+    uint64_t startedAt = 0;
+
+    static FunctionRunLog fromJson(const nlohmann::json& j);
+    nlohmann::json toJson() const;
+};
+
+/// Append-only per-project run log in `<project>:vectorapi_function_runs`.
+///
+/// Trimmed on write rather than by a background job: there is no scheduler yet,
+/// and an unbounded log on a busy function is how a database fills up quietly.
+class FunctionRunLogStore {
+public:
+    FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction);
+
+    void ensure(const std::string& project);
+    void append(const std::string& project, const FunctionRunLog& entry);
+    std::vector<FunctionRunLog> list(const std::string& project, const std::string& functionId,
+                                     uint32_t limit);
+
+private:
+    DbGateway& db_;
+    uint32_t keep_;
+    std::string coll(const std::string& project) const {
+        return qualify(project, "vectorapi_function_runs");
+    }
+};
+
+} // namespace svapi

+ 342 - 0
src/handlers/function_dispatch.cpp

@@ -0,0 +1,342 @@
+// Public dispatch of user functions under /fn/*.
+//
+// This is the only route group in the server with NO authentication: the
+// pre-routing handler authenticates /api/* and nothing else, exactly as it
+// leaves /healthz and /docs open (handlers/meta.cpp). A function that serves
+// HTTP is published on purpose, so the gate is the registry - `enabled` and
+// `valid` - not a key.
+//
+// Because it is public, everything below treats the request path as hostile.
+#include "auth.hpp"
+#include "errors.hpp"
+#include "functions/descriptor.hpp"
+#include "json_http.hpp"
+#include "server.hpp"
+#include <algorithm>
+#include <ctime>
+#include <spdlog/spdlog.h>
+
+namespace svapi {
+namespace {
+
+/// Response headers a function may not set: httplib owns the framing, and a
+/// function that could forge Content-Length or Transfer-Encoding could smuggle
+/// a second response past any proxy in front of us.
+bool reservedResponseHeader(const std::string& lower) {
+    static const char* kReserved[] = {"content-length", "transfer-encoding", "connection",
+                                      "keep-alive",     "upgrade",           "trailer",
+                                      "te",             "host"};
+    for (const char* r : kReserved) if (lower == r) return true;
+    return false;
+}
+
+/// Request headers never forwarded into user code.
+///
+/// Cookie is the dangerous one: the web UI is served from this same origin, so
+/// a logged-in admin's browser attaches the session cookie to /fn/* as well,
+/// and forwarding it would hand that admin's session to every function author
+/// in the project. Authorization goes for the same reason.
+bool secretRequestHeader(const std::string& lower) {
+    return lower == "cookie" || lower == "set-cookie" || lower == "authorization"
+        || lower == "proxy-authorization" || lower == "x-captcha-token";
+}
+
+std::string lowerCase(std::string s) {
+    std::transform(s.begin(), s.end(), s.begin(),
+                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
+    return s;
+}
+
+/// A project name we are willing to put through qualify(). Deliberately
+/// stricter than the database's own rules: ':' is the project/collection
+/// separator qualify() builds on, '/' and '.' are path tricks, and anything
+/// outside this set has no business naming a project. Rejecting here means the
+/// unvetted segment never reaches a collection name.
+bool safeProjectSegment(const std::string& p) {
+    if (p.empty() || p.size() > 64) return false;
+    if (p == "." || p == "..") return false;
+    for (unsigned char c : p) {
+        const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
+                     || (c >= '0' && c <= '9') || c == '-' || c == '_';
+        if (!ok) return false;
+    }
+    return true;
+}
+
+/// httplib percent-decodes before we see the path, so "%2e%2e" arrives as "..".
+/// A ".." segment can never match a literal pattern segment, but it CAN be
+/// captured by a `:name` parameter and handed to a function that uses it as a
+/// key, so it is refused at the edge instead.
+bool hasDotDotSegment(const std::string& path) {
+    size_t i = 0;
+    while (i < path.size()) {
+        const size_t end = path.find('/', i);
+        const std::string seg = path.substr(i, end == std::string::npos ? end : end - i);
+        if (seg == "..") return true;
+        if (end == std::string::npos) break;
+        i = end + 1;
+    }
+    return false;
+}
+
+nlohmann::json headerJson(const httplib::Request& req) {
+    nlohmann::json out = nlohmann::json::object();
+    for (const auto& [name, value] : req.headers) {
+        const std::string lower = lowerCase(name);
+        if (secretRequestHeader(lower)) continue;
+        // Lower-cased keys so a script can look one up without guessing the
+        // casing a client happened to send.
+        out[lower] = value;
+    }
+    return out;
+}
+
+/// Repeated query keys collapse to the last value, because the trigger shape is
+/// fixed at {method, path, params, query, headers, body} and `query` is an
+/// object. A function needing `?tag=a&tag=b` needs that shape widened first;
+/// guessing an array here would make the field's type depend on the request.
+nlohmann::json queryJson(const httplib::Request& req) {
+    nlohmann::json out = nlohmann::json::object();
+    for (const auto& [name, value] : req.params) out[name] = value;
+    return out;
+}
+
+/// JSON when the request says JSON and it parses, the raw string otherwise,
+/// null when there is no body. A parse failure is NOT a 400: the function may
+/// legitimately accept text with a wrong content type, and guessing on its
+/// behalf would make /fn/* stricter than the function it fronts.
+nlohmann::json triggerBody(const httplib::Request& req) {
+    if (req.body.empty()) return nullptr;
+    const std::string ct = lowerCase(req.get_header_value("Content-Type"));
+    if (ct.find("json") != std::string::npos) {
+        try {
+            return nlohmann::json::parse(req.body);
+        } catch (const std::exception&) {
+            // fall through to the raw string
+        }
+    }
+    return req.body;
+}
+
+nlohmann::json routeParamsJson(const functions::RouteParams& params) {
+    nlohmann::json out = nlohmann::json::object();
+    for (const auto& [k, v] : params) out[k] = v;
+    return out;
+}
+
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+
+/// An unresolvable /fn path. One shape for "no such project", "no such
+/// function", "disabled" and "invalid": a public route must not let an
+/// unauthenticated caller enumerate which projects or functions exist.
+void sendNotFound(httplib::Response& res) {
+    sendJson(res, 404, errorBody("not_found", "no function serves this route"));
+}
+
+/// Write a successful run's own response. The function chose the status, the
+/// headers and the body; our job is only to stop it breaking the protocol.
+void sendFunctionResponse(httplib::Response& res, const RunnerRunResult& r) {
+    int status = r.status;
+    if (status < 100 || status > 599) status = 200;  // a nonsense status is not a response
+    res.status = status;
+
+    std::string contentType;
+    int emitted = 0;
+    if (r.headers.is_object()) {
+        for (const auto& [name, value] : r.headers.items()) {
+            if (++emitted > 32) break;  // a header flood is a denial of service, not a response
+            if (!value.is_string()) continue;
+            const std::string lower = lowerCase(name);
+            if (reservedResponseHeader(lower)) continue;
+            if (lower == "content-type") { contentType = value.get<std::string>(); continue; }
+            res.set_header(name, value.get<std::string>());
+        }
+    }
+
+    if (r.body.is_null()) {
+        if (!contentType.empty()) res.set_header("Content-Type", contentType);
+        return;  // no body; a 204 stays a 204
+    }
+    if (r.body.is_string()) {
+        res.set_content(r.body.get<std::string>(),
+                        contentType.empty() ? "text/plain; charset=utf-8" : contentType);
+        return;
+    }
+    res.set_content(r.body.dump(), contentType.empty() ? "application/json" : contentType);
+}
+
+/// Writing the log must never change the answer: a database hiccup on an
+/// append would otherwise turn a function that worked into a 500.
+void recordRun(ServerDeps& d, const std::string& project, const FunctionRunLog& entry) {
+    try {
+        d.functionRuns.append(project, entry);
+    } catch (const std::exception& e) {
+        spdlog::warn("could not record run {} of {}/{}: {}", entry.runId, project,
+                     entry.functionId, e.what());
+    }
+}
+
+void dispatch(ServerDeps& d, const httplib::Request& req, httplib::Response& res) {
+    const std::string project = req.matches[1];
+    std::string path = req.matches.size() > 2 ? std::string(req.matches[2]) : std::string();
+    if (path.empty()) path = "/";
+
+    if (!safeProjectSegment(project) || hasDotDotSegment(path)) { sendNotFound(res); return; }
+
+    // The project must exist before anything qualifies a collection with it, so
+    // a crafted segment cannot conjure a registry read in a namespace of its own.
+    const std::vector<std::string> projects = d.db.listProjects();
+    if (std::find(projects.begin(), projects.end(), project) == projects.end()) {
+        sendNotFound(res);
+        return;
+    }
+
+    std::vector<FunctionRecord> rows = d.functions.list(project);
+    // matchHttpRoute resolves ties by declaration order, so the order we hand it
+    // decides which function serves an overlapping route. The database makes no
+    // promise about list() order, so sort: the same two functions must not swap
+    // a shared route across a restart.
+    std::sort(rows.begin(), rows.end(),
+              [](const FunctionRecord& a, const FunctionRecord& b) {
+                  return a.functionId < b.functionId;
+              });
+
+    std::vector<functions::FunctionDescriptor> descriptors;
+    std::vector<std::string> ids;
+    descriptors.reserve(rows.size());
+    ids.reserve(rows.size());
+    for (const FunctionRecord& row : rows) {
+        // A disabled or invalid function is invisible, not 403: a public caller
+        // learns nothing about what the project holds.
+        if (!row.enabled || !row.valid) continue;
+        functions::ParseResult parsed = functions::parseDescriptor(row.descriptor);
+        if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Http) continue;
+        descriptors.push_back(std::move(parsed.descriptor));
+        ids.push_back(row.functionId);
+    }
+
+    const functions::RouteMatch match = functions::matchHttpRoute(descriptors, req.method, path);
+    if (match.status == functions::RouteMatchStatus::NotFound) { sendNotFound(res); return; }
+    if (match.status == functions::RouteMatchStatus::MethodNotAllowed) {
+        // 405 and 404 stay distinct, and a 405 owes the client an Allow header.
+        res.set_header("Allow", functions::allowHeaderValue(match.allowedMethods));
+        sendJson(res, 405, errorBody("method_not_allowed",
+                                     "this route does not serve " + req.method));
+        return;
+    }
+
+    // match.descriptor borrows from `descriptors`, which has not been touched
+    // since, so its offset is the index of the record it came from.
+    const size_t idx = static_cast<size_t>(match.descriptor - descriptors.data());
+    const std::string functionId = ids[idx];
+
+    const std::string runId = randomToken();
+    FunctionRunLog entry;
+    entry.runId = runId;
+    entry.functionId = functionId;
+    entry.trigger = "http";
+    entry.startedAt = nowSec();
+
+    if (!d.runners) {
+        // Nothing to dispatch to. Still logged: "the function was reached but no
+        // runner existed" is the operational fact worth having.
+        entry.ok = false;
+        entry.status = 503;
+        entry.error = "no runner configured";
+        recordRun(d, project, entry);
+        sendJson(res, 503, errorBody("runner_unavailable", "no function runner is configured"));
+        return;
+    }
+
+    const nlohmann::json trigger{{"method", req.method},
+                                 {"path", path},
+                                 {"params", routeParamsJson(match.params)},
+                                 {"query", queryJson(req)},
+                                 {"headers", headerJson(req)},
+                                 {"body", triggerBody(req)}};
+
+    const RunnerRunResult r = d.runners->run(project, functionId, trigger);
+
+    entry.ok = r.ok;
+    entry.durationMs = r.durationMs;
+    entry.console = r.console;
+    entry.error = r.error;
+
+    // The status mapping. Three of these four are OUR fault or OUR limit, so
+    // none of them exposes the function's error text to an unauthenticated
+    // caller - the full message goes to the run log, which the project's own
+    // people read through GET .../functions/{id}/logs.
+    if (r.transportFailure) {
+        // We never got an answer from any runner. 503 with Retry-After, because
+        // the same request may well succeed once a runner is back.
+        entry.status = 503;
+        res.set_header("Retry-After", "5");
+        sendJson(res, 503, errorBody("runner_unavailable", "no function runner is available"));
+    } else if (r.timedOut) {
+        // 504: the thing we delegated to never finished. Not 408 - nothing was
+        // slow about the client.
+        entry.status = httpStatus(ErrCode::GatewayTimeout);
+        sendJson(res, entry.status,
+                 errorBody("function_timeout", "the function exceeded its time limit",
+                           {{"function_id", functionId}, {"run_id", runId}}));
+    } else if (r.outOfMemory) {
+        // 500, not 503: the function asked for more memory than it may have, so
+        // the identical request will fail identically and "come back later" would
+        // be a lie. Not 507 either - that is about storage, and inventing a rare
+        // status buys a client nothing it can act on.
+        entry.status = 500;
+        sendJson(res, 500, errorBody("function_out_of_memory",
+                                     "the function exceeded its memory limit",
+                                     {{"function_id", functionId}, {"run_id", runId}}));
+    } else if (!r.ok) {
+        // The function threw. 500, the same answer an unhandled exception in our
+        // own handlers gets: from the caller's side this IS the server. Not 502 -
+        // the runner is an implementation detail, not an upstream the client
+        // asked us to proxy.
+        entry.status = 500;
+        sendJson(res, 500, errorBody("function_error", "the function failed",
+                                     {{"function_id", functionId}, {"run_id", runId}}));
+    } else {
+        entry.status = r.status;
+        sendFunctionResponse(res, r);
+    }
+
+    recordRun(d, project, entry);
+}
+
+} // namespace
+
+void registerFunctionDispatchRoutes(ApiServer& s) {
+    auto& svr = s.raw();
+    ServerDeps* d = &s.deps();
+
+    // Project in the path, because there is no key to read one from.
+    //
+    // The alternatives were a single configured dispatch project (one project
+    // gets public functions, the rest silently cannot - and it needs a config
+    // field this change does not own) and a Host-header map (right answer for
+    // custom domains, but it needs that same config and a vhost table). Naming
+    // the project in the path needs neither, and it matches the shape every
+    // other route already has: /api/v1/projects/{p}/... .
+    //
+    // It does mean any caller can address any project's functions by naming it.
+    // That is addressing, not a leak: a published HTTP function is published,
+    // and a project name is not a credential. What must not happen is a crafted
+    // path reaching a project the caller did not name, which is why the segment
+    // is charset-checked, confirmed against listProjects(), and used for exactly
+    // one registry read - and why the remainder is matched ONLY against that
+    // project's descriptors.
+    const char* pattern = R"(/fn/([^/]+)((?:/.*)?))";
+    auto handler = [d](const httplib::Request& req, httplib::Response& res) {
+        dispatch(*d, req, res);
+    };
+    svr.Get(pattern, handler);
+    svr.Post(pattern, handler);
+    svr.Put(pattern, handler);
+    svr.Patch(pattern, handler);
+    svr.Delete(pattern, handler);
+    // No HEAD: cpp-httplib has no registrar for it, so a HEAD never reaches a
+    // handler. OPTIONS is answered by the server-wide CORS pre-flight route.
+}
+
+} // namespace svapi

+ 328 - 0
src/handlers/functions.cpp

@@ -0,0 +1,328 @@
+#include "errors.hpp"
+#include "function_record.hpp"
+#include "json_http.hpp"
+#include "project_settings.hpp"
+#include "server.hpp"
+#include <cstdlib>
+#include <ctime>
+#include <limits>
+
+namespace svapi {
+namespace {
+
+/// The runner pool, or 503.
+///
+/// "No runner configured" and "every runner is down" are the same answer to the
+/// caller: the route exists, the capability behind it does not right now. It is
+/// never a 404 - a 404 would say the function feature is not part of this API.
+RunnerPool& requireRunner(ServerDeps& d) {
+    if (d.runners == nullptr)
+        throw ApiError(ErrCode::Unavailable, "no_runner",
+                       "no function runner is configured on this server");
+    if (!d.runners->anyHealthy())
+        throw ApiError(ErrCode::Unavailable, "no_runner",
+                       "no healthy function runner is available");
+    return *d.runners;
+}
+
+/// What a code push carries. `policy` is deliberately absent: see below.
+struct CodePush {
+    std::string source;
+    std::string path;
+};
+
+CodePush codePush(const nlohmann::json& body) {
+    if (!body.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "the body must be an object");
+    if (!body.contains("source") || !body["source"].is_string() ||
+        body["source"].get<std::string>().empty())
+        throw ApiError(ErrCode::Unprocessable, "validation", "source is required");
+    if (body.contains("path") && !body["path"].is_string())
+        throw ApiError(ErrCode::Unprocessable, "validation", "path must be a string");
+    // A `policy` field in a code push is IGNORED, not rejected: a client that
+    // GETs a function and PUTs it back would otherwise be unable to write at
+    // all, and ignoring the field has no escalation failure mode, while
+    // "is this narrower than what is stored?" is where one would live (design
+    // doc, Addendum). Policy changes go through the admin-only policy route.
+    return {body["source"].get<std::string>(), body.value("path", "")};
+}
+
+/// Compile the push on a runner and turn the result into a storable row.
+///
+/// The engine that validates is the engine that will execute, so nothing is
+/// stored that has not compiled on a real runner.
+FunctionRecord validateOnRunner(ServerDeps& d, const CodePush& push) {
+    RunnerValidateResult v = requireRunner(d).validate(push.source, push.path);
+    if (v.transportFailure)
+        throw ApiError(ErrCode::Unavailable, "runner_unreachable",
+                       v.error.empty() ? "the function runner could not be reached" : v.error);
+    if (!v.ok)
+        throw ApiError(ErrCode::Unprocessable, "compile_failed",
+                       v.error.empty() ? "the function did not compile" : v.error);
+
+    const std::string declared =
+        v.descriptor.is_object() ? v.descriptor.value("id", std::string()) : std::string();
+    if (declared.empty())
+        throw ApiError(ErrCode::Unprocessable, "missing_function_id",
+                       "the script's `on` block must declare an id; the file path is never "
+                       "used as a fallback");
+
+    FunctionRecord rec;
+    rec.functionId  = declared;
+    rec.path        = push.path;
+    rec.source      = push.source;
+    rec.contentHash = functionContentHash(push.source);
+    rec.descriptor  = v.descriptor;
+    rec.valid       = true;
+    return rec;
+}
+
+/// The policy a first registration inherits: the project's configured
+/// `default_function_policy`, else the built-in floor, which grants no
+/// collection at all.
+///
+/// Only ever consulted for a FIRST registration - mergeForCodePush keeps an
+/// existing function's policy - so changing a project's default never
+/// retroactively alters anything already deployed.
+KeyScope projectDefaultPolicy(ServerDeps& d, const std::string& project) {
+    const auto proj = d.settings.projectSnapshot(project);
+    return defaultFunctionPolicyFor(proj.get());
+}
+
+/// Validate and read a policy document. Shaped like keys.cpp parseScope, with
+/// one deliberate difference: an empty rule set is legal here. It is the
+/// deny-everything default a function starts on, so an admin must be able to
+/// put it back.
+KeyScope parsePolicy(const nlohmann::json& body) {
+    // {"policy":{...}} and a bare scope object are both unambiguous, so both
+    // are accepted - the admin UI sends the first, a curl the second.
+    const nlohmann::json& p = body.contains("policy") ? body.at("policy") : body;
+    if (!p.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "policy must be an object");
+    if (p.contains("rules")) {
+        if (!p["rules"].is_array())
+            throw ApiError(ErrCode::Unprocessable, "validation", "policy.rules must be an array");
+        for (const auto& r : p["rules"]) {
+            if (!r.is_object() || r.value("collection", std::string()).empty())
+                throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs a collection");
+            if (!r.contains("ops") || !r["ops"].is_array() || r["ops"].empty())
+                throw ApiError(ErrCode::Unprocessable, "validation", "each rule needs ops");
+            for (const auto& o : r["ops"])
+                if (!o.is_string() || !keyOpFromString(o.get<std::string>()))
+                    throw ApiError(ErrCode::Unprocessable, "validation", "unknown op in policy");
+        }
+    }
+    return KeyScope::fromJson(p);
+}
+
+/// A function that cannot run, as an error - or nothing.
+///
+/// 409 rather than 422: the request is fine, the server's state refuses it, and
+/// the caller fixes it by enabling or re-pushing the function, not by editing
+/// the request.
+void requireRunnable(const FunctionRecord& fn) {
+    if (!fn.valid)
+        throw ApiError(ErrCode::Conflict, "function_invalid",
+                       fn.lastError.empty() ? "this function is marked invalid" : fn.lastError);
+    if (!fn.enabled)
+        throw ApiError(ErrCode::Conflict, "function_disabled", "this function is disabled");
+}
+
+uint32_t limitParam(const httplib::Request& req, uint32_t fallback) {
+    if (!req.has_param("limit")) return fallback;
+    const std::string raw = req.get_param_value("limit");
+    if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
+        throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer");
+    unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
+    if (wide == 0 || wide > std::numeric_limits<uint32_t>::max())
+        throw ApiError(ErrCode::Unprocessable, "validation", "limit must be a positive integer");
+    return static_cast<uint32_t>(wide);
+}
+
+/// The trigger a manual invoke synthesises. Every field is optional: invoking a
+/// function with no body is the common case ("does it still run?"), so the
+/// defaults have to produce a usable request.
+nlohmann::json manualTrigger(const FunctionRecord& fn, const nlohmann::json& body) {
+    const std::string route =
+        fn.descriptor.is_object() ? fn.descriptor.value("route", std::string()) : std::string();
+    nlohmann::json t;
+    t["method"]  = body.value("method", std::string("POST"));
+    t["path"]    = body.value("path", route);
+    t["params"]  = body.contains("params") && body["params"].is_object()
+                       ? body["params"] : nlohmann::json::object();
+    t["query"]   = body.contains("query") && body["query"].is_object()
+                       ? body["query"] : nlohmann::json::object();
+    t["headers"] = body.contains("headers") && body["headers"].is_object()
+                       ? body["headers"] : nlohmann::json::object();
+    t["body"]    = body.contains("body") ? body["body"] : nlohmann::json();
+    return t;
+}
+
+nlohmann::json runEnvelope(const std::string& runId, const RunnerRunResult& r) {
+    return {{"run_id", runId},
+            {"ok", r.ok},
+            {"status", r.status},
+            {"headers", r.headers},
+            {"body", r.body},
+            {"console", r.console},
+            {"duration_ms", r.durationMs},
+            {"error", r.error},
+            {"timed_out", r.timedOut},
+            {"out_of_memory", r.outOfMemory}};
+}
+
+}  // namespace
+
+void registerFunctionRoutes(ApiServer& s) {
+    auto& svr = s.raw(); ServerDeps* d = &s.deps();
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/functions)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireProjectManage(requireKey(*d, req), project);
+        d->functions.ensure(project);
+        nlohmann::json arr = nlohmann::json::array();
+        // Summaries, never full rows: a listing that shipped every function's
+        // source would grow without bound in the one response people poll.
+        for (const auto& fn : d->functions.list(project)) arr.push_back(fn.toSummaryJson());
+        sendJson(res, 200, {{"functions", arr}});
+    });
+
+    svr.Post(R"(/api/v1/projects/([^/]+)/functions)",
+             [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireProjectManage(requireKey(*d, req), project);
+        FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
+        // POST creates. An id that already exists is a genuine conflict, and
+        // answering 409 keeps a second author from quietly overwriting the
+        // first's code just because both chose the same `on.id`.
+        if (d->functions.get(project, incoming.functionId))
+            throw ApiError(ErrCode::Conflict, "function_exists",
+                           "a function with this id already exists - PUT it to update",
+                           {{"function_id", incoming.functionId}});
+        FunctionRecord stored =
+            d->functions.put(project, incoming, projectDefaultPolicy(*d, project));
+        sendJson(res, 201, stored.toSummaryJson());
+    });
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        auto fn = d->functions.get(project, id);
+        if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, fn->toJson());   // the single-function view carries the source
+    });
+
+    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        FunctionRecord incoming = validateOnRunner(*d, codePush(bodyJson(req)));
+        // The id lives in the source, so the URL cannot rename a function. Say
+        // which is which: silently trusting either one would either move the
+        // code to another function's row or move a policy to other code.
+        if (incoming.functionId != id)
+            throw ApiError(ErrCode::Unprocessable, "id_mismatch",
+                           "the script's `on` block declares id '" + incoming.functionId +
+                               "' but the URL names '" + id +
+                               "' - the id is part of the source, not of the URL",
+                           {{"declared", incoming.functionId}, {"url", id}});
+        const bool existed = d->functions.get(project, id).has_value();
+        // put() preserves the stored policy and enabled flag via
+        // mergeForCodePush, which is why a push can never widen access.
+        FunctionRecord stored =
+            d->functions.put(project, incoming, projectDefaultPolicy(*d, project));
+        sendJson(res, existed ? 200 : 201, stored.toSummaryJson());
+    });
+
+    svr.Delete(R"(/api/v1/projects/([^/]+)/functions/([^/]+))",
+               [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        if (!d->functions.remove(project, id))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, {{"deleted", id}});
+    });
+
+    // ADMIN ONLY, and the only route that changes a policy. Developers push
+    // code, admins grant what it may touch - the same split keys already have.
+    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/policy)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireAdmin(requireKey(*d, req));
+        KeyScope policy = parsePolicy(bodyJson(req));
+        if (!d->functions.setPolicy(project, id, policy))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        auto fn = d->functions.get(project, id);
+        if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, fn->toSummaryJson());
+    });
+
+    svr.Put(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/enabled)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        auto body = bodyJson(req);
+        if (!body.contains("enabled") || !body["enabled"].is_boolean())
+            throw ApiError(ErrCode::Unprocessable, "validation", "enabled must be a boolean");
+        if (!d->functions.setEnabled(project, id, body["enabled"].get<bool>()))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        sendJson(res, 200, {{"function_id", id}, {"enabled", body["enabled"].get<bool>()}});
+    });
+
+    svr.Post(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/invoke)",
+             [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        auto fn = d->functions.get(project, id);
+        if (!fn) throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        requireRunnable(*fn);
+        RunnerPool& pool = requireRunner(*d);
+
+        const nlohmann::json body = req.body.empty() ? nlohmann::json::object() : bodyJson(req);
+        // A run id is just a random token with no secret meaning; generateApiKey
+        // is reused rather than adding a second hex generator.
+        const std::string runId = generateApiKey();
+        const uint64_t startedAt = static_cast<uint64_t>(std::time(nullptr));
+        RunnerRunResult r = pool.run(project, id, manualTrigger(*fn, body));
+
+        FunctionRunLog entry;
+        entry.runId      = runId;
+        entry.functionId = id;
+        entry.trigger    = "invoke";
+        entry.ok         = r.ok;
+        entry.status     = r.status;
+        entry.durationMs = r.durationMs;
+        entry.error      = r.error;
+        entry.console    = r.console;
+        entry.startedAt  = startedAt;
+        // Logged before the 503 below: an attempt that never reached a runner is
+        // exactly the one an operator goes looking for afterwards.
+        d->functionRuns.append(project, entry);
+
+        if (r.transportFailure)
+            throw ApiError(ErrCode::Unavailable, "runner_unreachable",
+                           r.error.empty() ? "the function runner could not be reached" : r.error,
+                           {{"run_id", runId}});
+        // 200 even when the function itself failed: an invoke REPORTS a run, it
+        // does not serve it. The function's own status lives in the envelope, and
+        // flattening it into the HTTP status would make "the function returned
+        // 500" indistinguishable from "the invoke could not be performed".
+        sendJson(res, 200, runEnvelope(runId, r));
+    });
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/functions/([^/]+)/logs)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1], id = req.matches[2];
+        requireProjectManage(requireKey(*d, req), project);
+        if (!d->functions.get(project, id))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such function");
+        nlohmann::json arr = nlohmann::json::array();
+        for (const auto& e : d->functionRuns.list(project, id, limitParam(req, 50)))
+            arr.push_back(e.toJson());
+        sendJson(res, 200, {{"function_id", id}, {"runs", arr}});
+    });
+}
+
+}  // namespace svapi

+ 29 - 5
src/main.cpp

@@ -1,6 +1,7 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
 #include "config.hpp"
+#include <memory>
 #include "db_gateway.hpp"
 #include "key_store.hpp"
 #include "server.hpp"
@@ -70,15 +71,38 @@ int main(int argc, char** argv) {
     // from the API (GET /collections empty, document ops 404) even though the
     // data survives on disk. KeyStore::bootstrap already does this for
     // vectorapi_keys, which is why keys survive but the registry didn't. (issue #1)
-    {
-        auto projects = db.listProjects();  // always includes the default project
-        registry.bootstrap(projects);
-        spdlog::info("opened collection registry for {} project(s) at startup", projects.size());
+    const std::vector<std::string> projects = db.listProjects();  // includes the default
+    registry.bootstrap(projects);
+    spdlog::info("opened collection registry for {} project(s) at startup", projects.size());
+
+    svapi::FunctionRegistry functions(db);
+    svapi::FunctionRunLogStore functionRuns(db, cfg.functionRunsKept);
+    // Same reason CollectionRegistry::bootstrap exists: the database only
+    // surfaces a collection through find() once it has been opened in this
+    // process, so without this every project's function registry reads back
+    // empty after a restart even though the rows are on disk.
+    for (const std::string& project : projects) {
+        functions.ensure(project);
+        functionRuns.ensure(project);
+    }
+
+    // Null when no runners are configured, which the function routes report as
+    // 503 rather than as a missing feature.
+    std::unique_ptr<svapi::RunnerPool> runners;
+    if (!cfg.runnerEndpoints.empty()) {
+        svapi::RunnerPool::Options ro;
+        ro.endpoints = cfg.runnerEndpoints;
+        runners = std::make_unique<svapi::RunnerPool>(ro);
+        spdlog::info("function runners configured: {}", cfg.runnerEndpoints.size());
+    } else {
+        spdlog::info("no function runners configured - function routes will answer 503");
     }
 
     svapi::SessionStore sessions(std::chrono::minutes(settings.snapshot()->sessionTtlMinutes));
 
-    svapi::ServerDeps deps{db, settings, keys, registry, sessions, cfg.webuiDir, shareDir};
+    svapi::ServerDeps deps{db,        settings,     keys,          registry,
+                           sessions,  functions,    functionRuns,  runners.get(),
+                           cfg.webuiDir, shareDir};
     svapi::ApiServer server(std::move(deps));
     server.registerRoutes();
 

+ 305 - 0
src/runner_client.cpp

@@ -0,0 +1,305 @@
+#include "runner_client.hpp"
+#include <httplib.h>
+#include <spdlog/spdlog.h>
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+// Why no applyOutboundDefaults() here: that helper exists for calls that leave
+// our trust boundary (embedding providers, captcha verification), where a
+// provider must see our User-Agent and must not be able to bounce a
+// credentialed request elsewhere. A runner is a first-party process from this
+// repo, addressed by a configured host:port and speaking a private protocol -
+// not a provider. Treating it as one would also drag vectorapi_core's whole
+// dependency set into a client that deliberately needs nothing but httplib,
+// which is what keeps this file testable on a host with no database client. The
+// two properties of that helper that DO matter internally are set explicitly
+// below: redirects off, and TLS verification on for an https endpoint.
+template <class Opts>
+void configureClient(httplib::Client& cli, const Opts& o) {
+    cli.set_connection_timeout(o.connectTimeoutSec, 0);
+    cli.set_read_timeout(o.readTimeoutSec, 0);
+    cli.set_write_timeout(o.readTimeoutSec, 0);
+    // A runner has no business redirecting us anywhere, and following one would
+    // turn a compromised or misconfigured runner into an SSRF primitive.
+    cli.set_follow_location(false);
+    cli.set_keep_alive(true);
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+    cli.enable_server_certificate_verification(true);
+#endif
+}
+
+/// "host:port" -> "http://host:port"; an explicit scheme is kept. Trailing
+/// slashes are dropped so the base concatenates cleanly with "/run".
+std::string normalizeBase(std::string e) {
+    while (!e.empty() && e.back() == '/') e.pop_back();
+    if (e.find("://") == std::string::npos) e = "http://" + e;
+    return e;
+}
+
+/// httplib errors that prove the request never left us, so nothing ran and the
+/// next endpoint is safe to try. Everything else - a read timeout above all -
+/// means the runner may have received the request and executed the function.
+bool neverDelivered(httplib::Error e) {
+    return e == httplib::Error::Connection || e == httplib::Error::ConnectionTimeout;
+}
+
+std::string errorText(httplib::Error e) { return httplib::to_string(e); }
+
+std::vector<std::string> consoleLines(const nlohmann::json& j) {
+    std::vector<std::string> out;
+    if (!j.contains("console") || !j["console"].is_array()) return out;
+    const nlohmann::json& arr = j["console"];  // bind first: a range-for over a temporary dangles
+    for (const nlohmann::json& line : arr)
+        out.push_back(line.is_string() ? line.get<std::string>() : line.dump());
+    return out;
+}
+
+// The three helpers below are templated only so they can name RunnerPool's
+// private Endpoint type by deduction: the seam header declares no private
+// helper methods and is not ours to change, so the shared state transitions
+// live here instead of being copy-pasted into each public method.
+
+/// Indices to try, in round-robin order, skipping endpoints still inside their
+/// backoff window. Advances the rotation by one so successive calls spread.
+template <class Eps>
+std::vector<size_t> pickCandidates(Eps& eps, size_t& next, std::mutex& mu) {
+    const auto now = std::chrono::steady_clock::now();
+    std::vector<size_t> out;
+    std::lock_guard<std::mutex> lk(mu);
+    if (eps.empty()) return out;
+    const size_t start = next++ % eps.size();
+    for (size_t n = 0; n < eps.size(); ++n) {
+        const size_t i = (start + n) % eps.size();
+        // An expired backoff puts an endpoint back in rotation even while the
+        // flag still says unhealthy: the flag is a hint, the clock decides.
+        if (eps[i].healthy || now >= eps[i].notBefore) out.push_back(i);
+    }
+    return out;
+}
+
+template <class Eps>
+void markHealthy(Eps& eps, size_t i, std::mutex& mu) {
+    std::lock_guard<std::mutex> lk(mu);
+    eps[i].healthy = true;
+    eps[i].notBefore = {};
+    eps[i].lastError.clear();
+}
+
+template <class Eps>
+void markUnhealthy(Eps& eps, size_t i, std::mutex& mu, uint32_t backoffSec,
+                   const std::string& why) {
+    std::lock_guard<std::mutex> lk(mu);
+    const bool wasHealthy = eps[i].healthy;
+    eps[i].healthy = false;
+    eps[i].lastError = why;
+    eps[i].notBefore = std::chrono::steady_clock::now() + std::chrono::seconds(backoffSec);
+    // Only on the transition, or a hard-down runner floods the log once per request.
+    if (wasHealthy) spdlog::warn("runner {} marked unhealthy: {}", eps[i].base, why);
+}
+
+/// Turn a protocol response into a run result. NEVER a transport failure:
+/// reaching here means a runner answered, so whatever went wrong is the
+/// function's, not ours. A thrown exception, a wall-time timeout and an
+/// out-of-memory kill all arrive this way - the runner did its job and reported
+/// the outcome, which is precisely why none of them is retried.
+RunnerRunResult parseRun(const nlohmann::json& j) {
+    RunnerRunResult out;
+    out.transportFailure = false;
+    out.timedOut = j.value("timed_out", false);
+    out.outOfMemory = j.value("out_of_memory", false);
+    out.error = j.value("error", std::string{});
+    // `ok` is honoured when the runner sends it, so a runner can report a
+    // failure that carries no message; otherwise it is derived.
+    out.ok = j.contains("ok") && j["ok"].is_boolean()
+                 ? j["ok"].get<bool>()
+                 : (out.error.empty() && !out.timedOut && !out.outOfMemory);
+    out.status = j.contains("status") && j["status"].is_number_integer()
+                     ? j["status"].get<int>() : 200;
+    if (j.contains("headers") && j["headers"].is_object()) out.headers = j["headers"];
+    if (j.contains("body")) out.body = j["body"];
+    out.console = consoleLines(j);
+    out.durationMs = j.value("duration_ms", static_cast<int64_t>(0));
+    return out;
+}
+
+} // namespace
+
+RunnerPool::RunnerPool(Options opts) : opts_(std::move(opts)) {
+    for (const std::string& e : opts_.endpoints) {
+        Endpoint ep;
+        ep.base = normalizeBase(e);
+        // Optimistically healthy: with no probe yet, refusing to dispatch would
+        // make a cold start look like an outage.
+        ep.healthy = true;
+        endpoints_.push_back(std::move(ep));
+    }
+}
+
+bool RunnerPool::anyHealthy() {
+    // Probes rather than trusting the cached flag: "answered /health recently"
+    // is a claim about the runner now, and a stale true is the dangerous
+    // direction - a function write would then be validated against nothing.
+    for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
+        std::string base;
+        { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
+        httplib::Client cli(base);
+        configureClient(cli, opts_);
+        httplib::Result r = cli.Get("/health");
+        if (r && r->status == 200) {
+            markHealthy(endpoints_, i, mu_);
+            return true;
+        }
+        markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                      r ? ("health status " + std::to_string(r->status)) : errorText(r.error()));
+    }
+    return false;
+}
+
+RunnerRunResult RunnerPool::run(const std::string& project, const std::string& functionId,
+                                const nlohmann::json& trigger) {
+    const nlohmann::json payload{{"project", project},
+                                 {"function_id", functionId},
+                                 {"trigger", trigger}};
+    RunnerRunResult last;
+    last.ok = false;
+    last.transportFailure = true;
+    last.status = 503;
+    last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
+
+    for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
+        std::string base;
+        { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
+        httplib::Client cli(base);
+        configureClient(cli, opts_);
+        httplib::Result r = cli.Post("/run", payload.dump(), "application/json");
+
+        if (!r) {
+            const std::string why = errorText(r.error());
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, why);
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner unreachable: " + why;
+            if (neverDelivered(r.error())) continue;  // nothing ran; the next runner is safe
+            // Delivered but unanswered: the handler may be running right now, so
+            // the caller gets an error and NOBODY runs it again.
+            spdlog::error("runner {} did not answer /run for {}/{}: {} - not retried, the run "
+                          "may already have had side effects", base, project, functionId, why);
+            return last;
+        }
+        if (r->status != 200) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "run status " + std::to_string(r->status));
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner returned HTTP " + std::to_string(r->status);
+            return last;  // off-protocol AFTER delivery: same reasoning as above
+        }
+
+        nlohmann::json j;
+        try {
+            j = nlohmann::json::parse(r->body);
+        } catch (const std::exception& e) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          std::string("unparseable /run response: ") + e.what());
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner response was not JSON";
+            return last;
+        }
+        if (!j.is_object()) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "non-object /run response");
+            last.transportFailure = true;
+            last.status = 503;
+            last.error = "runner response was not an object";
+            return last;
+        }
+
+        markHealthy(endpoints_, i, mu_);
+        return parseRun(j);
+    }
+    return last;
+}
+
+RunnerValidateResult RunnerPool::validate(const std::string& source, const std::string& path) {
+    const nlohmann::json payload{{"source", source}, {"path", path}};
+    RunnerValidateResult last;
+    last.ok = false;
+    last.transportFailure = true;
+    last.error = opts_.endpoints.empty() ? "no runner configured" : "no healthy runner";
+
+    for (size_t i : pickCandidates(endpoints_, next_, mu_)) {
+        std::string base;
+        { std::lock_guard<std::mutex> lk(mu_); base = endpoints_[i].base; }
+        httplib::Client cli(base);
+        configureClient(cli, opts_);
+        httplib::Result r = cli.Post("/validate", payload.dump(), "application/json");
+
+        // Unlike run(), EVERY failure here is retryable. Compiling a script and
+        // reading its `on` block has no side effects, so a second attempt
+        // elsewhere can only turn a 503 into an answer; the double-execution
+        // hazard that constrains run() does not exist on this path.
+        if (!r) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec, errorText(r.error()));
+            last.transportFailure = true;
+            last.error = "runner unreachable: " + errorText(r.error());
+            continue;
+        }
+        if (r->status != 200) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "validate status " + std::to_string(r->status));
+            last.transportFailure = true;
+            last.error = "runner returned HTTP " + std::to_string(r->status);
+            continue;
+        }
+        nlohmann::json j;
+        try {
+            j = nlohmann::json::parse(r->body);
+        } catch (const std::exception& e) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          std::string("unparseable /validate response: ") + e.what());
+            last.transportFailure = true;
+            last.error = "runner response was not JSON";
+            continue;
+        }
+        if (!j.is_object()) {
+            markUnhealthy(endpoints_, i, mu_, opts_.unhealthyBackoffSec,
+                          "non-object /validate response");
+            last.transportFailure = true;
+            last.error = "runner response was not an object";
+            continue;
+        }
+
+        markHealthy(endpoints_, i, mu_);
+        RunnerValidateResult out;
+        out.transportFailure = false;
+        out.ok = j.value("ok", false);
+        out.error = j.value("error", std::string{});
+        if (j.contains("descriptor") && j["descriptor"].is_object())
+            out.descriptor = j["descriptor"];
+        return out;
+    }
+    return last;
+}
+
+nlohmann::json RunnerPool::statusJson() {
+    const auto now = std::chrono::steady_clock::now();
+    nlohmann::json arr = nlohmann::json::array();
+    size_t healthyCount = 0;
+    std::lock_guard<std::mutex> lk(mu_);
+    for (const Endpoint& ep : endpoints_) {
+        int64_t retryIn = 0;
+        if (!ep.healthy && ep.notBefore > now)
+            retryIn = std::chrono::duration_cast<std::chrono::seconds>(ep.notBefore - now).count();
+        if (ep.healthy) ++healthyCount;
+        arr.push_back({{"endpoint", ep.base},
+                       {"healthy", ep.healthy},
+                       {"last_error", ep.lastError},
+                       {"retry_in_sec", retryIn}});
+    }
+    return {{"runners", arr}, {"healthy", healthyCount}};
+}
+
+} // namespace svapi

+ 101 - 0
src/runner_client.hpp

@@ -0,0 +1,101 @@
+#pragma once
+#include <nlohmann/json.hpp>
+#include <chrono>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// What one runner reported for one run.
+struct RunnerRunResult {
+    bool ok = false;
+    int status = 200;
+    nlohmann::json headers = nlohmann::json::object();
+    nlohmann::json body;
+    std::vector<std::string> console;
+    int64_t durationMs = 0;
+    std::string error;
+    bool timedOut = false;
+    bool outOfMemory = false;
+    /// True when no runner gave a usable answer, as opposed to a runner
+    /// reporting that the function failed. The two map to different HTTP
+    /// statuses: the first is our problem, the second is the function's.
+    ///
+    /// Covers both "never connected" and the more dangerous "connected, then
+    /// gave nothing usable" - a read timeout, a non-200, an unparseable body.
+    /// Only the first of those is safe to retry, because in the second the
+    /// handler may be running right now; see the three-way split in
+    /// runner_client.cpp.
+    bool transportFailure = false;
+};
+
+struct RunnerValidateResult {
+    bool ok = false;
+    /// The parsed `on` block, when the script compiled.
+    nlohmann::json descriptor;
+    std::string error;
+    bool transportFailure = false;
+};
+
+/// A static list of runners, health-checked, used round-robin.
+///
+/// Discovery is a config list on purpose: dynamic registration is only worth its
+/// failure modes once autoscaling exists. A run is retried on the next healthy
+/// runner, because a runner dying between the health check and the request is
+/// ordinary, not exceptional.
+class RunnerPool {
+public:
+    struct Options {
+        std::vector<std::string> endpoints;  // "host:port" or full base URLs
+        uint32_t connectTimeoutSec = 2;
+        /// MUST exceed the runner's `max_wall_time_ms`, or our read times out
+        /// before the runner can report its own timeout and the caller gets a
+        /// 503 ("no runner available") instead of the truthful 504. The
+        /// defaults here and in runner/config/runner.json satisfy that with
+        /// room to spare (30 s against 2 s); raising the runner's ceiling means
+        /// raising this too.
+        uint32_t readTimeoutSec = 30;
+        /// How long a failed runner is skipped before being retried.
+        uint32_t unhealthyBackoffSec = 10;
+    };
+
+    explicit RunnerPool(Options opts);
+
+    /// True when at least one runner answered /health recently. Creating or
+    /// updating a function requires this: a write is validated by the engine
+    /// that will execute it, so with no runner there is nothing to validate
+    /// against and the write is refused with 503 rather than stored unchecked.
+    bool anyHealthy();
+
+    /// POST /run on the first healthy runner. Retried on the next endpoint ONLY
+    /// when the connection was never established, so nothing can have run: a
+    /// request that was delivered and then went unanswered is NOT retried,
+    /// because the handler may be executing and a retry would run a
+    /// side-effecting function twice. `trigger` is
+    /// {method, path, params, query, headers, body}.
+    RunnerRunResult run(const std::string& project, const std::string& functionId,
+                        const nlohmann::json& trigger);
+
+    /// POST /validate - compile `source` and parse its `on` block without
+    /// running the handler.
+    RunnerValidateResult validate(const std::string& source, const std::string& path);
+
+    /// Endpoints with their last known health, for the admin UI and /healthz.
+    nlohmann::json statusJson();
+
+private:
+    struct Endpoint {
+        std::string base;
+        bool healthy = true;
+        std::chrono::steady_clock::time_point notBefore{};
+        std::string lastError;
+    };
+    Options opts_;
+    std::mutex mu_;
+    std::vector<Endpoint> endpoints_;
+    size_t next_ = 0;
+};
+
+} // namespace svapi

+ 8 - 0
src/server.cpp

@@ -111,6 +111,9 @@ void ApiServer::registerRoutes() {
         if (res.status == 404 && req.method == "GET" && !d_.webuiDir.empty()
             && req.path.rfind("/api/", 0) != 0
             && req.path.rfind("/ui/", 0) != 0
+            // /fn/* is user function dispatch: a path that matches no function
+            // owes the caller a real 404, not the SPA shell with status 200.
+            && req.path.rfind("/fn/", 0) != 0
             && req.path.rfind("/docs", 0) != 0
             && req.path != "/openapi.json" && req.path != "/llms.txt"
             && req.path != "/healthz" && req.path != "/readyz"
@@ -166,6 +169,11 @@ void ApiServer::registerRoutes() {
     registerSettingsRoutes(*this);
     registerProjectSettingsRoutes(*this);
     registerRelationRoutes(*this);
+    registerFunctionRoutes(*this);
+    // LAST. Function dispatch owns /fn/* , and registering it after the
+    // built-in routes means a user function can never shadow one of them even
+    // if cpp-httplib's matching order ever changes.
+    registerFunctionDispatchRoutes(*this);
 
     if (!d_.shareDir.empty()) svr_.set_mount_point("/docs", d_.shareDir + "/docs");
     if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);

+ 12 - 0
src/server.hpp

@@ -3,7 +3,10 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
 #include "db_gateway.hpp"
+#include "function_registry.hpp"
+#include "function_run_log.hpp"
 #include "principal.hpp"
+#include "runner_client.hpp"
 #include "key_store.hpp"
 #include "settings_store.hpp"
 #include <httplib.h>
@@ -18,6 +21,11 @@ struct ServerDeps {
     KeyStore& keys;
     CollectionRegistry& registry;
     SessionStore& sessions;
+    FunctionRegistry& functions;
+    FunctionRunLogStore& functionRuns;
+    /// Null when no runner endpoints are configured: the function routes then
+    /// answer 503 rather than pretending the feature is absent.
+    RunnerPool* runners = nullptr;
     std::string webuiDir;   // static SPA root ("" disables)
     std::string shareDir;   // openapi.json + llms.txt dir
 };
@@ -82,5 +90,9 @@ void registerStatsRoutes(ApiServer&);
 void registerSettingsRoutes(ApiServer&);
 void registerProjectSettingsRoutes(ApiServer&);
 void registerRelationRoutes(ApiServer&);
+void registerFunctionRoutes(ApiServer&);
+// Registered LAST: it claims /fn/* , and a function route must never shadow
+// a built-in /api/* route.
+void registerFunctionDispatchRoutes(ApiServer&);
 
 } // namespace svapi

+ 27 - 0
tests/CMakeLists.txt

@@ -111,3 +111,30 @@ target_include_directories(test_function_record PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_function_record PRIVATE
     nlohmann_json::nlohmann_json OpenSSL::Crypto GTest::gtest_main)
 gtest_discover_tests(test_function_record)
+
+# The run-log store against a link-time fake database: the test defines the few
+# Client members the store calls, so this target must NOT link vectorapi_core,
+# which would bring the real client back and fail to link on the dev host. It
+# needs the client's headers only.
+add_executable(test_function_run_log
+    test_function_run_log.cpp
+    ${CMAKE_SOURCE_DIR}/src/function_run_log.cpp)
+target_include_directories(test_function_run_log PRIVATE
+    ${CMAKE_SOURCE_DIR}/src
+    $<TARGET_PROPERTY:smartbotic::db-client,INTERFACE_INCLUDE_DIRECTORIES>)
+target_link_libraries(test_function_run_log PRIVATE
+    nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_function_run_log)
+
+# RunnerPool talks to nothing but httplib, so this target compiles its source
+# directly rather than linking vectorapi_core, and still builds and runs on a
+# host where smartbotic-db-client cannot compile.
+add_executable(test_runner_client
+    test_runner_client.cpp
+    ${CMAKE_SOURCE_DIR}/src/runner_client.cpp)
+target_include_directories(test_runner_client PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_compile_definitions(test_runner_client PRIVATE CPPHTTPLIB_OPENSSL_SUPPORT)
+target_link_libraries(test_runner_client PRIVATE
+    httplib::httplib nlohmann_json::nlohmann_json spdlog::spdlog
+    OpenSSL::SSL OpenSSL::Crypto GTest::gtest_main)
+gtest_discover_tests(test_runner_client)

+ 9 - 1
tests/api_fixture.hpp

@@ -16,6 +16,8 @@ class ApiFixture : public ::testing::Test {
 protected:
     std::unique_ptr<DbGateway> db_;
     std::unique_ptr<CollectionRegistry> registry_;
+    std::unique_ptr<FunctionRegistry> functions_;
+    std::unique_ptr<FunctionRunLogStore> functionRuns_;
     std::unique_ptr<SettingsStore> settings_;
     std::unique_ptr<KeyStore> keys_;
     std::unique_ptr<SessionStore> sessions_;
@@ -49,6 +51,8 @@ protected:
         db_->ensureProject(project_);
 
         registry_ = std::make_unique<CollectionRegistry>(*db_);
+        functions_ = std::make_unique<FunctionRegistry>(*db_);
+        functionRuns_ = std::make_unique<FunctionRunLogStore>(*db_, 50);
         registry_->ensure(project_);
         settings_ = std::make_unique<SettingsStore>(*db_, settingsColl_, "current");
         settings_->bootstrap("");
@@ -76,7 +80,11 @@ protected:
         std::ofstream(webuiDir_ + "/index.html")
             << "<!doctype html><html><head><title>SVAPI_SPA_OK</title></head><body><div id=\"root\"></div></body></html>";
 
-        ServerDeps deps{*db_, *settings_, *keys_, *registry_, *sessions_, webuiDir_, apiDocsDir()};
+        // `runners` stays null: these tests have no function runner, and the
+        // function routes answer 503 for that, which is itself worth asserting.
+        ServerDeps deps{*db_,      *settings_,  *keys_,         *registry_,
+                        *sessions_, *functions_, *functionRuns_, nullptr,
+                        webuiDir_,  apiDocsDir()};
         server_ = std::make_unique<ApiServer>(std::move(deps));
         server_->registerRoutes();
         port_ = server_->bindToAnyPort("127.0.0.1");

+ 213 - 0
tests/test_function_run_log.cpp

@@ -0,0 +1,213 @@
+// FunctionRunLogStore against a fake database.
+//
+// The fake is supplied at LINK time: this file defines the handful of
+// `smartbotic::database::Client` members function_run_log.cpp calls, so the
+// target never links the real client. That is what makes the trim rule - the
+// one piece of behaviour here worth asserting - testable on a host where
+// libsmartbotic-db-client cannot be linked at all (CLAUDE.md, "The Void dev
+// host can no longer build the C++ natively").
+//
+// Every stub ignores `this` and works on the file-static `g_db` below, so no
+// Client or DbGateway object is ever constructed or read; the references handed
+// to the store point at storage nothing dereferences.
+#include "function_run_log.hpp"
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <map>
+
+using nlohmann::json;
+using Client = smartbotic::database::Client;
+
+namespace {
+
+/// collection -> document id -> body.
+std::map<std::string, std::map<std::string, json>> g_db;
+std::map<std::string, bool> g_created;
+
+void resetDb() { g_db.clear(); g_created.clear(); }
+
+}  // namespace
+
+namespace smartbotic::database {
+
+bool Client::createCollection(const std::string& name, uint32_t, bool, uint32_t, uint32_t) {
+    g_created[name] = true;
+    g_db[name];
+    return true;
+}
+
+std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
+    if (!g_created.count(name)) return std::nullopt;
+    CollectionInfo info;
+    info.name = name;
+    info.documentCount = g_db[name].size();
+    return info;
+}
+
+std::pair<std::string, bool> Client::upsert(const std::string& collection, const json& data,
+                                            const std::string& id, uint32_t, const std::string&) {
+    const bool isNew = g_db[collection].count(id) == 0;
+    json body = data;
+    body.erase("id");  // the real client strips a top-level `id` from the body
+    g_db[collection][id] = std::move(body);
+    return {id, isNew};
+}
+
+bool Client::remove(const std::string& collection, const std::string& id) {
+    return g_db[collection].erase(id) > 0;
+}
+
+std::vector<json> Client::find(const std::string& collection, const QueryOptions& options) {
+    std::vector<json> rows;
+    for (const auto& [id, body] : g_db[collection]) {
+        bool keep = true;
+        for (const auto& f : options.filters) {
+            // Only the one operator the store uses; anything else is a test bug.
+            EXPECT_EQ(static_cast<int>(f.op), static_cast<int>(FilterOp::EQ));
+            if (body.value(f.field, json()) != f.value) { keep = false; break; }
+        }
+        if (keep) rows.push_back(body);
+    }
+    if (!options.sortField.empty()) {
+        const std::string& key = options.sortField;
+        std::stable_sort(rows.begin(), rows.end(), [&](const json& a, const json& b) {
+            const uint64_t av = a.value(key, 0ull), bv = b.value(key, 0ull);
+            return options.sortDescending ? av > bv : av < bv;
+        });
+    }
+    std::vector<json> page;
+    for (size_t i = options.offset; i < rows.size() && page.size() < options.limit; ++i)
+        page.push_back(rows[i]);
+    return page;
+}
+
+}  // namespace smartbotic::database
+
+namespace svapi {
+
+/// Mirrors db_gateway.cpp. That translation unit cannot be linked here: it
+/// constructs a real Client, whose PIMPL lives in the library this target
+/// exists to avoid. The store only needs the mapping to be injective per
+/// project, which this is.
+std::string qualify(const std::string& project, const std::string& collection) {
+    if (project.empty() || project == "default") return collection;
+    return project + ":" + collection;
+}
+
+Client& DbGateway::client() {
+    alignas(Client) static unsigned char storage[sizeof(void*) * 4];
+    return *reinterpret_cast<Client*>(storage);
+}
+
+}  // namespace svapi
+
+namespace {
+
+/// A DbGateway reference whose object is never touched: every call reaching it
+/// lands in a stub above.
+svapi::DbGateway& fakeGateway() {
+    alignas(svapi::DbGateway) static unsigned char storage[sizeof(void*) * 8];
+    return *reinterpret_cast<svapi::DbGateway*>(storage);
+}
+
+svapi::FunctionRunLog entry(const std::string& runId, const std::string& fnId, uint64_t startedAt) {
+    svapi::FunctionRunLog e;
+    e.runId      = runId;
+    e.functionId = fnId;
+    e.trigger    = "invoke";
+    e.ok         = true;
+    e.status     = 200;
+    e.durationMs = 7;
+    e.startedAt  = startedAt;
+    return e;
+}
+
+class FunctionRunLogTest : public ::testing::Test {
+protected:
+    void SetUp() override { resetDb(); }
+};
+
+TEST_F(FunctionRunLogTest, RoundTripsEveryField) {
+    svapi::FunctionRunLog e = entry("r1", "kb-search", 1700000000);
+    e.ok      = false;
+    e.status  = 500;
+    e.error   = "TypeError: x is not a function";
+    e.console = {"first", "second"};
+
+    const svapi::FunctionRunLog back = svapi::FunctionRunLog::fromJson(e.toJson());
+    EXPECT_EQ(back.runId, "r1");
+    EXPECT_EQ(back.functionId, "kb-search");
+    EXPECT_EQ(back.trigger, "invoke");
+    EXPECT_FALSE(back.ok);
+    EXPECT_EQ(back.status, 500);
+    EXPECT_EQ(back.durationMs, 7);
+    EXPECT_EQ(back.error, "TypeError: x is not a function");
+    EXPECT_EQ(back.console, std::vector<std::string>({"first", "second"}));
+    EXPECT_EQ(back.startedAt, 1700000000u);
+}
+
+// `run_id`, not `id`: the client strips a top-level `id`, which would leave a
+// stored run with no identity to delete by.
+TEST_F(FunctionRunLogTest, StoresItsIdInTheBody) {
+    EXPECT_TRUE(svapi::FunctionRunLog().toJson().contains("run_id"));
+    EXPECT_FALSE(svapi::FunctionRunLog().toJson().contains("id"));
+}
+
+TEST_F(FunctionRunLogTest, AbsentFieldsDoNotInventARun) {
+    const svapi::FunctionRunLog e = svapi::FunctionRunLog::fromJson(json::object());
+    EXPECT_TRUE(e.runId.empty());
+    EXPECT_FALSE(e.ok);        // a row with no verdict is not a success
+    EXPECT_EQ(e.status, 0);
+    EXPECT_TRUE(e.console.empty());
+}
+
+TEST_F(FunctionRunLogTest, AppendKeepsOnlyTheNewestPerFunction) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 3);
+    for (uint64_t i = 1; i <= 6; ++i)
+        store.append("p1", entry("r" + std::to_string(i), "fn", 1000 + i));
+
+    const auto rows = store.list("p1", "fn", 100);
+    ASSERT_EQ(rows.size(), 3u);
+    EXPECT_EQ(rows[0].runId, "r6");   // newest first
+    EXPECT_EQ(rows[1].runId, "r5");
+    EXPECT_EQ(rows[2].runId, "r4");
+}
+
+// Trimming is per function, so a chatty function cannot evict a quiet one's
+// history out from under an operator reading it.
+TEST_F(FunctionRunLogTest, TrimIsScopedToOneFunction) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 2);
+    store.append("p1", entry("q1", "quiet", 1));
+    for (uint64_t i = 1; i <= 5; ++i)
+        store.append("p1", entry("c" + std::to_string(i), "chatty", 100 + i));
+
+    EXPECT_EQ(store.list("p1", "quiet", 100).size(), 1u);
+    EXPECT_EQ(store.list("p1", "chatty", 100).size(), 2u);
+}
+
+TEST_F(FunctionRunLogTest, KeepZeroMeansKeepEverything) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 0);
+    for (uint64_t i = 1; i <= 10; ++i)
+        store.append("p1", entry("r" + std::to_string(i), "fn", i));
+    EXPECT_EQ(store.list("p1", "fn", 100).size(), 10u);
+}
+
+// A listing can never return more than is kept, so the store clamps rather
+// than letting ?limit=1000000 become a million-row query.
+TEST_F(FunctionRunLogTest, ListClampsLimitToWhatIsKept) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 4);
+    for (uint64_t i = 1; i <= 4; ++i)
+        store.append("p1", entry("r" + std::to_string(i), "fn", i));
+    EXPECT_EQ(store.list("p1", "fn", 1000000).size(), 4u);
+    EXPECT_EQ(store.list("p1", "fn", 2).size(), 2u);
+}
+
+TEST_F(FunctionRunLogTest, ProjectsDoNotShareARunLog) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 10);
+    store.append("p1", entry("a", "fn", 1));
+    store.append("p2", entry("b", "fn", 1));
+    ASSERT_EQ(store.list("p1", "fn", 10).size(), 1u);
+    EXPECT_EQ(store.list("p1", "fn", 10)[0].runId, "a");
+}
+
+}  // namespace

+ 407 - 0
tests/test_runner_client.cpp

@@ -0,0 +1,407 @@
+// RunnerPool unit tests.
+//
+// Every test here runs against a real cpp-httplib server in-process, so the
+// pool's HTTP path is exercised for real without a QuickJS runner and without
+// the database client - which is what lets this target build on the dev host
+// (CLAUDE.md, "The Void dev host can no longer build the C++ natively").
+//
+// The test this file exists for is RunFailureIsNotRetried. Everything else
+// guards it: if a runner answering "your function threw" were treated as a
+// transport failure, the pool would run a side-effecting function a second time
+// on the next runner, and nothing in production would report that it had.
+
+#include "runner_client.hpp"
+#include <gtest/gtest.h>
+#include <httplib.h>
+#include <atomic>
+#include <memory>
+#include <string>
+#include <thread>
+
+using namespace svapi;
+using nlohmann::json;
+
+namespace {
+
+// 127.0.0.1:1 refuses immediately instead of timing out: a dead endpoint has to
+// be deterministic, and "bind a port then close it" races with the next test.
+constexpr const char* kDeadEndpoint = "127.0.0.1:1";
+
+/// A runner stand-in: counts requests per path and replies with whatever the
+/// test configured.
+class FakeRunner {
+public:
+    FakeRunner() = default;
+    ~FakeRunner() { stop(); }
+
+    /// Replies to POST /run with `status` and `body` verbatim.
+    void onRun(int status, std::string body) {
+        runStatus_ = status;
+        runBody_ = std::move(body);
+    }
+    void onValidate(int status, std::string body) {
+        validateStatus_ = status;
+        validateBody_ = std::move(body);
+    }
+    void healthy(bool v) { healthy_ = v; }
+
+    void start() {
+        svr_.Get("/health", [this](const httplib::Request&, httplib::Response& res) {
+            ++healthCalls_;
+            res.status = healthy_ ? 200 : 500;
+            res.set_content(healthy_ ? R"({"status":"ok"})" : R"({"status":"bad"})",
+                            "application/json");
+        });
+        svr_.Post("/run", [this](const httplib::Request& req, httplib::Response& res) {
+            ++runCalls_;
+            lastRunBody_ = req.body;
+            res.status = runStatus_;
+            res.set_content(runBody_, "application/json");
+        });
+        svr_.Post("/validate", [this](const httplib::Request& req, httplib::Response& res) {
+            ++validateCalls_;
+            lastValidateBody_ = req.body;
+            res.status = validateStatus_;
+            res.set_content(validateBody_, "application/json");
+        });
+        port_ = svr_.bind_to_any_port("127.0.0.1");
+        thread_ = std::thread([this] { svr_.listen_after_bind(); });
+        svr_.wait_until_ready();
+    }
+
+    void stop() {
+        if (!thread_.joinable()) return;
+        svr_.stop();
+        thread_.join();
+    }
+
+    std::string endpoint() const { return "127.0.0.1:" + std::to_string(port_); }
+    int runCalls() const { return runCalls_; }
+    int healthCalls() const { return healthCalls_; }
+    int validateCalls() const { return validateCalls_; }
+    const std::string& lastRunBody() const { return lastRunBody_; }
+    const std::string& lastValidateBody() const { return lastValidateBody_; }
+
+private:
+    httplib::Server svr_;
+    std::thread thread_;
+    int port_ = 0;
+    std::atomic<bool> healthy_{true};
+    std::atomic<int> healthCalls_{0}, runCalls_{0}, validateCalls_{0};
+    int runStatus_ = 200;
+    int validateStatus_ = 200;
+    std::string runBody_ = R"({"status":200,"body":{}})";
+    std::string validateBody_ = R"({"ok":true,"descriptor":{}})";
+    std::string lastRunBody_, lastValidateBody_;
+};
+
+RunnerPool::Options opts(std::vector<std::string> endpoints, uint32_t backoffSec = 10) {
+    RunnerPool::Options o;
+    o.endpoints = std::move(endpoints);
+    o.connectTimeoutSec = 2;
+    o.readTimeoutSec = 5;
+    o.unhealthyBackoffSec = backoffSec;
+    return o;
+}
+
+const json kTrigger = json{{"method", "GET"}, {"path", "/kb/x"},
+                           {"params", json::object()}, {"query", json::object()},
+                           {"headers", json::object()}, {"body", nullptr}};
+
+} // namespace
+
+// ---------------------------------------------------------------- no endpoints
+
+TEST(RunnerPool, NoEndpointsIsNeverHealthy) {
+    RunnerPool pool(opts({}));
+    EXPECT_FALSE(pool.anyHealthy());
+    EXPECT_TRUE(pool.statusJson()["runners"].empty());
+}
+
+TEST(RunnerPool, NoEndpointsFailsAsTransport) {
+    RunnerPool pool(opts({}));
+    RunnerRunResult r = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(r.ok);
+    EXPECT_TRUE(r.transportFailure);
+    EXPECT_FALSE(r.error.empty());
+
+    RunnerValidateResult v = pool.validate("export default () => {}", "a.js");
+    EXPECT_FALSE(v.ok);
+    EXPECT_TRUE(v.transportFailure);
+}
+
+// -------------------------------------------------------------- normalisation
+
+TEST(RunnerPool, EndpointFormsNormaliseToTheSameBase) {
+    RunnerPool pool(opts({"127.0.0.1:9100", "http://127.0.0.1:9100/", "http://127.0.0.1:9100"}));
+    const json s = pool.statusJson();
+    ASSERT_EQ(s["runners"].size(), 3u);
+    for (const json& e : s["runners"])
+        EXPECT_EQ(e["endpoint"].get<std::string>(), "http://127.0.0.1:9100");
+}
+
+TEST(RunnerPool, HttpsEndpointKeepsItsScheme) {
+    RunnerPool pool(opts({"https://runner.internal:8443/"}));
+    EXPECT_EQ(pool.statusJson()["runners"][0]["endpoint"].get<std::string>(),
+              "https://runner.internal:8443");
+}
+
+// --------------------------------------------------------------------- health
+
+TEST(RunnerPool, HealthProbeMarksReachableAndUnreachable) {
+    FakeRunner r;
+    r.start();
+    RunnerPool pool(opts({kDeadEndpoint, r.endpoint()}));
+    EXPECT_TRUE(pool.anyHealthy());
+    EXPECT_GE(r.healthCalls(), 1);
+
+    const json s = pool.statusJson();
+    ASSERT_EQ(s["runners"].size(), 2u);
+    EXPECT_FALSE(s["runners"][0]["healthy"].get<bool>());
+    EXPECT_FALSE(s["runners"][0]["last_error"].get<std::string>().empty());
+    EXPECT_TRUE(s["runners"][1]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, NonOkHealthStatusIsUnhealthy) {
+    FakeRunner r;
+    r.healthy(false);
+    r.start();
+    RunnerPool pool(opts({r.endpoint()}));
+    EXPECT_FALSE(pool.anyHealthy());
+    EXPECT_FALSE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+// ------------------------------------------------------------------------ run
+
+TEST(RunnerPool, RunParsesTheRunnerResponse) {
+    FakeRunner r;
+    r.onRun(200, R"({"status":201,"headers":{"X-A":"b"},"body":{"hits":2},
+                     "console":["one","two"],"duration_ms":7})");
+    r.start();
+    RunnerPool pool(opts({r.endpoint()}));
+
+    RunnerRunResult res = pool.run("proj", "kb-search", kTrigger);
+    EXPECT_TRUE(res.ok);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(res.status, 201);
+    EXPECT_EQ(res.headers["X-A"].get<std::string>(), "b");
+    EXPECT_EQ(res.body["hits"].get<int>(), 2);
+    ASSERT_EQ(res.console.size(), 2u);
+    EXPECT_EQ(res.console[0], "one");
+    EXPECT_EQ(res.durationMs, 7);
+
+    // The wire payload is the protocol in the design doc, not a renaming of it.
+    const json sent = json::parse(r.lastRunBody());
+    EXPECT_EQ(sent["project"].get<std::string>(), "proj");
+    EXPECT_EQ(sent["function_id"].get<std::string>(), "kb-search");
+    EXPECT_EQ(sent["trigger"]["path"].get<std::string>(), "/kb/x");
+}
+
+// THE test. A runner that answers "the function threw" has done its job
+// correctly; re-running elsewhere would execute the function twice.
+TEST(RunnerPool, RunFailureIsNotRetried) {
+    FakeRunner first, second;
+    first.onRun(200, R"({"status":500,"error":"TypeError: x is not a function","duration_ms":3})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(res.ok);
+    EXPECT_FALSE(res.transportFailure) << "a function failure is not a transport failure";
+    EXPECT_EQ(res.error, "TypeError: x is not a function");
+    EXPECT_EQ(first.runCalls(), 1);
+    EXPECT_EQ(second.runCalls(), 0) << "the function must not run a second time";
+
+    // The runner that reported the failure is working, so it stays healthy.
+    EXPECT_TRUE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, TimeoutAndOomAreFunctionFailuresNotTransportFailures) {
+    FakeRunner first, second;
+    first.onRun(200, R"({"status":500,"error":"wall time exceeded","timed_out":true})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(res.ok);
+    EXPECT_TRUE(res.timedOut);
+    EXPECT_FALSE(res.outOfMemory);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(second.runCalls(), 0) << "a timed-out run may have had side effects already";
+}
+
+TEST(RunnerPool, OutOfMemoryIsReportedAndNotRetried) {
+    FakeRunner first, second;
+    first.onRun(200, R"({"status":500,"error":"out of memory","out_of_memory":true})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.outOfMemory);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(second.runCalls(), 0);
+}
+
+TEST(RunnerPool, UnreachableRunnerIsRetriedOnTheNext) {
+    FakeRunner live;
+    live.onRun(200, R"({"status":200,"body":{"ok":1}})");
+    live.start();
+    RunnerPool pool(opts({kDeadEndpoint, live.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.ok);
+    EXPECT_FALSE(res.transportFailure);
+    EXPECT_EQ(live.runCalls(), 1);
+    EXPECT_FALSE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, AllRunnersUnreachableIsATransportFailure) {
+    RunnerPool pool(opts({kDeadEndpoint, kDeadEndpoint}));
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_FALSE(res.ok);
+    EXPECT_TRUE(res.transportFailure);
+}
+
+// A runner that answers something other than the protocol is broken, not a
+// function that failed: we cannot tell whether the handler ran, so the caller
+// gets our-fault (transport) and nobody re-runs it.
+TEST(RunnerPool, UnparseableRunnerResponseIsTransportAndNotRetried) {
+    FakeRunner first, second;
+    first.onRun(200, "<html>bad gateway</html>");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.transportFailure);
+    EXPECT_FALSE(res.ok);
+    EXPECT_EQ(second.runCalls(), 0) << "the handler may already have run";
+    EXPECT_FALSE(pool.statusJson()["runners"][0]["healthy"].get<bool>());
+}
+
+TEST(RunnerPool, HttpErrorStatusFromTheRunnerIsTransportAndNotRetried) {
+    FakeRunner first, second;
+    first.onRun(503, R"({"error":"no capacity"})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerRunResult res = pool.run("p", "f", kTrigger);
+    EXPECT_TRUE(res.transportFailure);
+    EXPECT_EQ(second.runCalls(), 0);
+}
+
+// ------------------------------------------------------------- round robin
+
+TEST(RunnerPool, SuccessiveRunsRotateAcrossRunners) {
+    FakeRunner a, b;
+    a.start();
+    b.start();
+    RunnerPool pool(opts({a.endpoint(), b.endpoint()}));
+    for (int i = 0; i < 4; ++i) EXPECT_TRUE(pool.run("p", "f", kTrigger).ok);
+    EXPECT_EQ(a.runCalls(), 2);
+    EXPECT_EQ(b.runCalls(), 2);
+}
+
+// --------------------------------------------------------------- backoff
+
+// Three calls rotate 0,1,0 over two endpoints, so the broken endpoint is a
+// candidate on calls 1 and 3. Whether call 3 touches it is exactly the backoff.
+TEST(RunnerPool, BackoffSkipsAFailedRunnerUntilItExpires) {
+    FakeRunner broken, live;
+    broken.onRun(500, R"({"error":"boom"})");
+    broken.start();
+    live.start();
+
+    RunnerPool pool(opts({broken.endpoint(), live.endpoint()}, /*backoffSec=*/3600));
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    EXPECT_EQ(broken.runCalls(), 1) << "inside the backoff window the runner is skipped";
+}
+
+TEST(RunnerPool, ZeroBackoffRetriesTheFailedRunnerImmediately) {
+    FakeRunner broken, live;
+    broken.onRun(500, R"({"error":"boom"})");
+    broken.start();
+    live.start();
+
+    RunnerPool pool(opts({broken.endpoint(), live.endpoint()}, /*backoffSec=*/0));
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    pool.run("p", "f", kTrigger);
+    EXPECT_EQ(broken.runCalls(), 2) << "an expired backoff puts the runner back in rotation";
+}
+
+// Every endpoint unhealthy must not mean "no candidates forever": with the
+// backoff expired the pool tries again rather than failing closed on stale state.
+TEST(RunnerPool, AnEndpointPastItsBackoffIsAttemptedAgain) {
+    FakeRunner live;
+    live.start();
+    RunnerPool pool(opts({live.endpoint()}, /*backoffSec=*/0));
+    live.healthy(false);
+    EXPECT_FALSE(pool.anyHealthy());
+    live.healthy(true);
+    EXPECT_TRUE(pool.anyHealthy());
+}
+
+// -------------------------------------------------------------- validate
+
+TEST(RunnerPool, ValidateParsesDescriptor) {
+    FakeRunner r;
+    r.onValidate(200, R"({"ok":true,"descriptor":{"id":"kb","type":"http","route":"/kb"}})");
+    r.start();
+    RunnerPool pool(opts({r.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("export const on = {}", "kb.js");
+    EXPECT_TRUE(v.ok);
+    EXPECT_FALSE(v.transportFailure);
+    EXPECT_EQ(v.descriptor["id"].get<std::string>(), "kb");
+
+    const json sent = json::parse(r.lastValidateBody());
+    EXPECT_EQ(sent["source"].get<std::string>(), "export const on = {}");
+    EXPECT_EQ(sent["path"].get<std::string>(), "kb.js");
+}
+
+TEST(RunnerPool, ValidateCompileErrorIsNotATransportFailure) {
+    FakeRunner first, second;
+    first.onValidate(200, R"({"ok":false,"error":"SyntaxError: unexpected token"})");
+    first.start();
+    second.start();
+    RunnerPool pool(opts({first.endpoint(), second.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("oops(", "a.js");
+    EXPECT_FALSE(v.ok);
+    EXPECT_FALSE(v.transportFailure);
+    EXPECT_EQ(v.error, "SyntaxError: unexpected token");
+    EXPECT_EQ(second.validateCalls(), 0) << "a compile error is the same on every runner";
+}
+
+// Validation has no side effects, so unlike run() it may be retried after a
+// request that was delivered but never answered.
+TEST(RunnerPool, ValidateRetriesAnUnreachableRunner) {
+    FakeRunner live;
+    live.onValidate(200, R"({"ok":true,"descriptor":{"id":"kb"}})");
+    live.start();
+    RunnerPool pool(opts({kDeadEndpoint, live.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("export const on = {}", "kb.js");
+    EXPECT_TRUE(v.ok);
+    EXPECT_EQ(live.validateCalls(), 1);
+}
+
+TEST(RunnerPool, ValidateRetriesARunnerThatAnsweredOffProtocol) {
+    FakeRunner broken, live;
+    broken.onValidate(500, "nope");
+    broken.start();
+    live.onValidate(200, R"({"ok":true,"descriptor":{"id":"kb"}})");
+    live.start();
+    RunnerPool pool(opts({broken.endpoint(), live.endpoint()}));
+
+    RunnerValidateResult v = pool.validate("export const on = {}", "kb.js");
+    EXPECT_TRUE(v.ok) << "validate is pure, so a broken runner is worth retrying past";
+    EXPECT_EQ(live.validateCalls(), 1);
+}