فهرست منبع

docs: slice 1 status, and the decisions that closed the open questions

CLAUDE.md gains what a reader needs before touching this: the runner's
three layers and why they are split that way (what each must link decides
where it can be tested), the /fn/* route being unauthenticated and its
project segment therefore hostile input, the three-way retry rule, and
the readTimeoutSec > max_wall_time_ms constraint that otherwise turns a
truthful 504 into a misleading 503.

The spec records what shipped, which of its own "Still open" questions
the implementation answered and how, and the five that opened in their
place - runner authentication being the one that matters before anyone
runs a runner on a second host.

ctx.env is written down as deliberately deferred rather than quietly
missing: two independent implementations refused to guess where a
project's secrets live, which is the right instinct and also means a
function cannot hold a credential yet.
fszontagh 1 ماه پیش
والد
کامیت
1ab1f2487e
2فایلهای تغییر یافته به همراه54 افزوده شده و 1 حذف شده
  1. 6 1
      CLAUDE.md
  2. 48 0
      docs/superpowers/specs/2026-10-06-function-runtime-design.md

+ 6 - 1
CLAUDE.md

@@ -32,7 +32,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
 - `webui/` — React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
-- `runner/` — the function runner's QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
+- `runner/` — the **function runner service**, a second binary (`smartbotic-vectorapi-runner`). Three layers split by what they must link, which is also what decides where each can be tested: `runner_core` (QuickJS engine + pool, no database), `runner_protocol` (`/run`, `/validate`, `/health` as JSON in / JSON out, no transport and no database — which is why its 30 tests run on the dev host), `runner_host` (the `ctx.*` surface; links `vectorapi_core`). `src/main.cpp` is the only part that links the world and the only part the dev host cannot build. The QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
 - `api/` — `openapi.json` (3.1), `llms.txt` (llmstxt.org), `docs/` (Redoc page). Served at `/openapi.json`, `/llms.txt`, `/docs`. Shipped in the server `.deb`. **Keep these in sync when changing routes.**
 - `packaging/` — `build.sh` (`--local` + Docker trixie), `deb/create-debs.sh`, control templates, systemd unit, maintainer scripts. `docs/superpowers/` — design spec (esp. **Addendum A**) + the 3 implementation plans.
 
@@ -51,6 +51,11 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A code push can never widen access.** `mergeForCodePush()` (`function_record.hpp`, pure) takes `policy` and `enabled` from the stored row and **never reads the ones in the payload** - not unioned, not used as a fallback. A first registration inherits the project default. Identity is `function_id` from the script's `on` block and `path` carries no meaning, so a rename keeps the row and its policy.
 - `builtinDefaultFunctionPolicy()` grants **nothing**: unreviewed code reaches no collection until an admin says so. Widening it is a security-posture change, and a test asserts the current floor.
 - **Descriptor parsing never throws** (`functions/descriptor.hpp`, pure): a script author's typo is data. Unknown keys are ignored so a script written for a later server still loads. 404 and 405 stay distinct, so a 405 can carry its `Allow:` union.
+- **Routes:** functions are managed at `/api/v1/projects/{p}/functions*` (project-manage; **policy is admin-only**) and served to the world at **`/fn/{project}/*`**, which is **unauthenticated** — the project segment is therefore hostile input: charset-restricted (no `:`, the `qualify()` separator), confirmed against `listProjects()` before anything qualifies a collection, and a `..` segment is refused anywhere (httplib percent-decodes before the handler sees the path, and `..` can be captured by a `:name` param). Disabled and invalid functions are absent from the descriptor list, so they 404 rather than 403, and function error text never reaches the caller — it goes to the run log, with the `run_id` in the response.
+- **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
+- **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **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 misleading 503 instead of a 504.
+- **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving — re-resolving IS the rebinding window. One resolution, one classification.
+- **`ctx.env` is empty and functions cannot hold a secret yet**: nothing has decided where a project's secrets live or who may read them, and an empty env is the only answer that cannot leak one. The one piece of slice 1 deliberately deferred.
 - **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A custom blocklist from settings *replaces* the defaults rather than extending them.
 
 ## Data model & runtime config

+ 48 - 0
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -261,3 +261,51 @@ cycle may start depending on a GitHub fetch.
   window stays open.
 - **Return shape** of the default export, and who validates it.
 - **Unhandled rejections** in background microtasks after the handler returned.
+
+## Slice 1: what shipped
+
+Complete and green at 399/399 in the Debian 13 container with
+`BUILD_RUNNER=ON`: the Principal refactor, descriptor parsing and route
+matching, the SSRF guard, the function registry with policy as server state,
+the QuickJS engine and pool, the runner service (`ctx.*`, `/run`, `/validate`,
+`/health`, the binary), functions CRUD, HTTP dispatch at `/fn/{project}/*`,
+manual invoke, and run logs.
+
+**Deferred, and the only piece of slice 1 that did not ship: `ctx.env`.** The
+field exists and is always empty. Nothing in the design decides where a
+project's secrets are stored or who may read them, and an empty env is the only
+answer that cannot leak one. Two independent implementations arrived at the same
+refusal to guess. A function therefore cannot hold a credential, which also
+means `ctx.fetch` can currently only reach endpoints that need none. This wants
+its own cycle, next to the per-project embedding key that already exists.
+
+### Resolved from "Still open"
+
+- **Status mapping.** A function that threw → 500 (from the caller's side we
+  *are* the server; the runner is an implementation detail, not an upstream the
+  client asked us to proxy). Wall-time timeout → **504**, which needed a new
+  `ErrCode::GatewayTimeout`. Out of memory → 500, not 503: a per-run ceiling
+  breach is deterministic, so "come back later" would be a lie. No healthy
+  runner → 503 with `Retry-After`.
+- **Return shape.** An object whose keys are a non-empty subset of
+  `{status, headers, body}` is an envelope; anything else is the body of a 200;
+  an object that MIXES them fails the run. Both lenient and strict readings of
+  `{status: 200, docs: []}` are wrong and the strict one fails silently, which
+  is the bug `documentBody()` already fixed once.
+- **TOCTOU on `ctx.fetch`.** Closed. A hostname resolves exactly once and the
+  connection is pinned to a checked address.
+- **The SSRF replace-vs-union question.** Still open, and still a replace.
+
+### Newly open
+
+- **The runner has no authentication** and binds `127.0.0.1`. `RunnerPool` sends
+  no credential, so none was invented. This needs deciding before runners ever
+  sit on a shared network - which was the stated reason for making the runner a
+  separate service.
+- `listProjects()` runs on every `/fn/*` request: a database round trip on the
+  hot path, and the first thing to cache once anyone measures this.
+- `JsLimits` is fixed at construction, unlike every other setting in this
+  codebase, which hot-reloads. Changing the wall-time ceiling needs a restart.
+- Repeated query keys (`?tag=a&tag=b`) collapse to the last value, because the
+  trigger's `query` is an object. Widening it is a protocol change on both sides.
+- `HEAD` on `/fn/*` is unroutable: cpp-httplib has no `Server::Head` registrar.