Sfoglia il codice sorgente

feat: per-kind wall caps, per-project embedding timeouts, embedTimeoutMs

Four things, three of them found in the field by the consuming project.

A project's wall-time cap is now per run kind. One number applied to whichever
ceiling the kind selected, so capping a project's HTTP routes at 10 s also cut
its cron work to 10 s and the only safe setting was no cap at all.
PUT .../settings/functions takes {"max_wall_time_ms":{"http":n,"job":n}}; a
bare integer still sets both. FunctionView carries both and RunService::run
selects, because lookup() does not know how a run was triggered.

Embedding timeouts are now per-project and narrowing only, resolved by the same
resolveEmbedding() that picks the endpoint - so an override applies identically
inside a function and on an HTTP vector route. Effective = min(project,
global), because these govern a shared provider connection and the pooled
runtime waiting on it; an override that could raise them would let one tenant
hold both longer than the operator allowed.

embedTimeoutMs on .search()/.store() is implemented. It was accepted and
silently ignored for a whole release, which is how a consumer came to rely on a
bound that did not exist. It now bounds the whole call, is narrowing only,
answers 504 embedding_timeout, and a bad value is 422 rather than dropped.

And the bug behind all of it: a 10 s-budget run took 14314 ms. The read timeout
was clamped to the remaining budget, the connect timeout was not, and the two
are additive - so a connect stall spent the full configured 10 s outside the
budget. A blocking host call cannot be interrupted, because the wall budget is
enforced between bytecode ops and the engine never regains control while an
HTTP request is in flight; timeouts that already fit the budget are therefore
the only enforcement there is. resolveEmbedBudget() splits one budget across
connect and read, and a failed provider call finally logs a warning - before
this it was visible only to the tenant, never to the operator.

Also here:
- a recycled collection name no longer inherits the previous one's
  constraints. The repair was gated on getCollectionInfo(), which is false for
  exactly the names that need it: a poisoned name has no collection, only
  surviving index declarations. Measured against 2.12.0 data carried into
  2.12.2, where a fresh create inherited a unique index and the new owner's
  second write was refused. The regression test fails without the fix.
- collection delete drops the find(1000000)-plus-remove-each sweep. It worked
  around a June note that is stale: a drop, a same-name recreate and a
  similarity search return zero hits on 2.12.0 and 2.12.2 alike. Verified on
  both before removing it.
- the runner subscribes to project settings instead of polling a 15 s TTL,
  which is what made clearing a cap look broken.
- ScopedKeyRateLimited no longer fails when its three requests straddle a
  calendar-minute boundary.

814/814 natively and 814/814 in the Debian container.
fszontagh 1 mese fa
parent
commit
6bd1d7668c

+ 6 - 2
CLAUDE.md

@@ -63,12 +63,16 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`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.
 - **Triggers:** `http` (a route), `cron` (a schedule, with an IANA `tz` validated against the host tz database at PUSH time - an unknown zone is refused, never silently UTC), `db` (an INSERT/UPDATE/DELETE on a watched collection) and `job` (reached only by being enqueued, which is where slow work belongs). The scheduler and the event watcher live in **vectorapi**, because there must be exactly one of each; N runners each firing every cron is the obvious bug.
-- **Wall time has TWO ceilings** (`functions/wall_budget.hpp`): an HTTP one (~2 s, which `RunnerPool::readTimeoutSec` must exceed) and a JOB one, which is exempt because a queue-claimed run holds no socket. `RunService::run` takes the kind as a PARAMETER, never inferred from the descriptor, and defaults to Http - the narrow budget - so a caller that forgets is slow rather than dangerous. Precedence: `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`, resolved by the pure `resolveWallBudget()`. The engine's `JsLimits::wall_time_ms` is raised to the highest ceiling at construction, or the clamp inside `JsRuntime::run` would kill every job at the HTTP value.
+- **A blocking host call cannot be interrupted, so host timeouts ARE the enforcement.** The wall budget is enforced by a QuickJS interrupt handler that fires between bytecode ops; while an embedding or `ctx.fetch` request is in flight the engine never regains control, so the deadline is noticed only once the call returns. Bounding a host call therefore means handing the HTTP client timeouts that already fit the remaining budget - which is what `resolveEmbedBudget()` (`functions/embed_budget.hpp`, pure) does. It exists because a 10 s-budget run took **14314 ms**: the READ timeout was clamped to the budget and the CONNECT timeout was not, and the two are additive, so a connect stall burned the full `embedding_connect_timeout_sec` outside the budget. Connect gets at most HALF the available time (a reachable provider connects in well under a second, and a large connect allowance only starves the read phase). Below a 2 s budget the 1 s floor on each phase dominates and the worst case is 2 s - bounded, and stated rather than glossed over.
+- **Embedding timeouts are per-project and NARROWING ONLY**, resolved by the same `resolveEmbedding()` that picks the endpoint, so a project's override applies identically to a function and to an HTTP vector route. The effective value is `min(project, global)`: these govern a shared provider connection and a pooled runtime waiting on it, so an override that could RAISE them would let one tenant hold both longer than the operator allowed. A stored value above the global is kept rather than refused - it becomes effective if the global is later lowered. A zero override is "unset", never "no timeout", because 0 means no timeout to the HTTP client and that is precisely the unbounded call the split prevents.
+- **`embedTimeoutMs` on `.search()`/`.store()` is validated, not coerced.** A non-integer or non-positive value is 422, and exceeding it is **504** `embedding_timeout` (distinct from the run simply running out of budget, because the remedies differ). It went unnoticed for a release while being silently accepted and ignored, which is exactly why an unsupported option must be refused rather than dropped.
+- **Wall time has TWO ceilings** (`functions/wall_budget.hpp`): an HTTP one (~2 s, which `RunnerPool::readTimeoutSec` must exceed) and a JOB one, which is exempt because a queue-claimed run holds no socket. `RunService::run` takes the kind as a PARAMETER, never inferred from the descriptor, and defaults to Http - the narrow budget - so a caller that forgets is slow rather than dangerous. Precedence: `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`, resolved by the pure `resolveWallBudget()`. **The project cap is per kind** (`{http, job}` on `PUT /projects/{p}/settings/functions`): one number could not express "10 s for routes, 60 s for jobs", so capping a project's routes also cut its cron work and the only safe setting was no cap. `FunctionView` carries BOTH and `RunService::run` selects, because `lookup()` does not know how a run was triggered. The engine's `JsLimits::wall_time_ms` is raised to the highest ceiling at construction, or the clamp inside `JsRuntime::run` would kill every job at the HTTP value.
 - **Job runs draw from their OWN pool lane.** A lease is held for a run's whole duration, every `ctx.fetch` included, so without a lane N slow jobs leave one runtime for every interactive route and the second overlapping HTTP run blocks until the read timeout fires - a 503 from a healthy runner. Worst-case memory is `(pool + job_pool) x memory_limit_bytes`, so the two lanes ADD.
 - **The database-event loop guard reads the event's actor** (client 2.12.0). Every write a function makes is stamped `fn:<project>/<id>:<depth>` via the `actor` parameter, and `Event::actor` carries it back - so provenance costs nothing and lives in the audit trail, NOT in a field inside user documents (which would travel into every export forever). A chain is refused past `events.max_depth` generations and logged at error.
 - **Delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs again, so cron and db functions must be idempotent. `singleFlight` (default true for cron) skips a tick while the previous run is still going, which bounds stacking but is not exactly-once.
 - **`jobs.enabled` is OFF by default in the runner**, so a runner upgrade never starts draining a queue in a deployment whose server has no scheduler. On a host that wants cron it MUST be turned on, or the scheduler enqueues work nothing ever runs - the most confusing possible way for cron to look broken.
 - **Project secrets** live in `<project>:vectorapi_secrets`, encrypted and deliberately NOT in the collection registry - so the documents API and `ctx.collections` both 404 it, and even a policy granting every collection cannot read it. Writes are admin-only; no GET ever returns a value. A `SVAPI_FN_<project>__<NAME>` host variable WINS over a stored secret of the same name, which is the break-glass a stolen API credential cannot shadow.
+- **The runner SUBSCRIBES to project settings; it does not poll.** `ProjectWallMax` wraps a `SettingsStore` with `reloadAll()` plus `startWatch()`, so a changed cap reaches the next run immediately. It used to be a hand-rolled cache on a `project_budget_ttl_sec` TTL, which made clearing a cap look broken for up to 15 s and produced a false bug report. **`reloadAll()`, never `bootstrap()`** - bootstrap WRITES, seeding the settings document, and a runner must never author configuration it only reads.
 - **The runner's `runtime` ceilings are boot-time only**, unlike every hot-reloading setting in the server: QuickJS fixes a runtime's memory limit at creation, so changing one live would mean draining and recreating the whole pool. Editing them means restarting the runner - cheap, because vectorapi answers 503 for that moment and stores nothing unvalidated. By contrast `function_egress_blocked_cidrs` / `function_egress_allow_private` DO hot-reload, because they are read per run.
 - **`ctx.env` comes from the runner's environment, scoped per project**: `SVAPI_FN_<project>__<NAME>` in `/etc/smartbotic-vectorapi/runner.env` reaches that project's functions as `ctx.env.<NAME>`. The project is part of the variable name because one runner serves every project; nothing outside the `SVAPI_FN_` prefix is ever exposed, so the runner's own token and database address stay invisible to functions. Matched exactly and case-sensitively; the split is at the **first** `__`, so a project whose name contains `__` cannot carry secrets.
 - **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile.
@@ -83,7 +87,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 ## ⚠️ Gotchas (hard-won - don't relearn these)
 
 - **DB v2.3.1: `_`-prefixed collections misroute when project-qualified.** Writes land in MemoryStore (mirror skips `_`-names) but reads of `default:_foo` route to LMDB → null. → service collections use **no leading underscore** (`vectorapi_*`). Suspected DB bug.
-- **`dropCollection` does not undeclare the collection's indexes** (database 2.12.1). The documents and the collection metadata go; the declared indexes, unique ones included, and their postings stay. A collection later created under the same name therefore inherits a constraint nobody declared, so a legitimate write is refused as a duplicate and the new owner's own `POST /indexes` reports `already_existed` instead of validating their data. Collection-create (the invisible-orphan drop) and collection-delete both undeclare indexes first for this reason. Worse, once the collection is gone the declaration is **unreachable and unrepairable**: `getCollectionInfo` says absent, `listIndexes` still names the field, and `dropIndex`/`dropCollection` both return false without clearing it, so the name is permanently poisoned. Reported to the database session; `dropIndex` on an absent collection is the fix that would let an existing one be repaired.
+- **`dropCollection` left the collection's indexes declared, before database 2.12.2.** The documents and the metadata went; the declared indexes, unique ones included, stayed. A collection later created under the same name inherited a constraint nobody declared - a legitimate write refused as a duplicate, measured directly: a recycled name on 2.12.0 answered `unique constraint violated on recyc#sku`. Collection-create and collection-delete therefore undeclare indexes explicitly, which is idempotent on 2.12.2 and the correct behaviour against anything older. **The create-time repair must be gated on "is anything still attached to this name", NOT on `getCollectionInfo`** (`anythingAttachedTo()` in `handlers/collections.cpp`): a poisoned name has no collection, so a presence check skips the repair in exactly the case that needs it. 2.12.2 also made `dropIndex` work on an absent collection, which is what lets an already-poisoned name be repaired at all - on 2.12.1 nothing could clear one.
 - **The ApiFixture tests share one database and a FIXED project name** (`svapitest_apiproj`), so `ctest` must run **serially** - `-j` makes them delete each other's state - and the fixture has to purge the previous run itself. It drops each of the project's indexes before its collection, because neither `dropProject` nor `dropCollection` does (see the two caveats here). None of this shows up in `packaging/devstack`, whose database is new every time; it only appears once the suite runs against a persistent one, which the native host build now does.
 - **DB v2.3.1: `dropProject` does not physically purge collection data.** A recycled project name is otherwise blocked by stale collections/registry → the project-delete handler drops the registry + collections first, and collection-create drops invisible orphans (after the registry "exists" check).
 - **DB client strips an `id` field from stored doc bodies.** So API keys store their stable id as `key_id` in the body (exposed as `id` externally); document handlers strip `id` before insert and use the separate id param.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.5.1
+0.6.0

+ 7 - 5
api/llms.txt

@@ -146,9 +146,9 @@ A project can point its embeddings at its own provider endpoint, key and model,
 
 Precedence for one embedding call: the collection's own `embedding_model` wins, then the project override, then the global default. The endpoint and key are the project override when set, otherwise the global ones.
 
-- `GET  /api/v1/projects/{project}/settings/embeddings` - Return `{effective, inherited, overrides}`. Each carries `openai_api_base`, `default_embedding_model` and `openai_api_key_set` (bool). The API key itself is never returned. In `overrides`, an empty string means the field is inherited.
-- `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.
+- `GET  /api/v1/projects/{project}/settings/embeddings` - Return `{effective, inherited, overrides}`. Each carries `openai_api_base`, `default_embedding_model`, `openai_api_key_set` (bool), `embedding_connect_timeout_sec` and `embedding_read_timeout_sec`. The API key itself is never returned. In `overrides`, an empty string means an inherited string field and `null` an inherited timeout.
+- `PUT  /api/v1/projects/{project}/settings/embeddings` `{openai_api_base?, openai_api_key?, default_embedding_model?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?}` - Omit a field to leave it unchanged; send `null` to clear the override and inherit the global value. The two timeouts are seconds and **narrowing only**: the effective value is `min(project, global)`, so a project can tighten but never lengthen how long it may hold a shared provider connection. A value above the global one is stored rather than refused, and becomes meaningful if an operator later lowers the global. 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 embedding override, timeouts included; the project inherits the global settings again. It does **not** touch the project's function policy or wall-time caps, which live in the same document but are admin-only.
 
 ## Project secrets
 
@@ -171,7 +171,7 @@ Deleting a project deletes its secrets, so a recycled project name inherits noth
 
 ### Per-project function limits
 
-- `GET  /api/v1/projects/{project}/settings/functions` **(admin)** - `{max_wall_time_ms}`; null means the project inherits the runner's ceiling.
+- `GET|PUT /api/v1/projects/{project}/settings/functions` `{max_wall_time_ms}` (**admin only**) - The project's wall-time cap, now **per run kind**: `{"max_wall_time_ms": {"http": n|null, "job": n|null}}`. A bare integer is still accepted on PUT and sets BOTH kinds, and `null` clears both; an object sets only the keys it names. GET always returns the object form - a single number could not express "10 s for routes, 60 s for jobs", and leaving the old scalar in place would make a client that reads only it see `null` (no cap) while a cap was in force. Narrowing only: neither raises a ceiling.
 - `PUT  /api/v1/projects/{project}/settings/functions` `{max_wall_time_ms: int|null}` **(admin)** - the ceiling a function here may ask for with its own `timeoutMs`. It can only NARROW: the effective budget is `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`. Admin-only because it decides how long one project may hold a pooled runtime, and so how long it can delay every other project's interactive routes.
 
 **A job run and an HTTP run have different ceilings.** An HTTP route answers a caller holding a socket open (seconds); a queue-claimed run has nobody waiting (minutes, 120 s by default) and draws from its own pool lane, so a slow scheduled job cannot take the runtime an interactive route needs.
@@ -202,7 +202,9 @@ export default async function (ctx) {
 `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
 
 - `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
-- Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters})`, returning an **array** of hits, and `.store({text|vector, metadata})`. Embedding resolves through the normal precedence, so a project's provider override applies.
+- Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters, embedTimeoutMs?})`, returning an **array** of hits, and `.store({text|vector, metadata, embedTimeoutMs?})`. Embedding resolves through the normal precedence, so a project's provider override applies.
+- **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. Exceeding it is **504** `embedding_timeout`. A non-integer or non-positive value is **422**: it is validated rather than ignored, because an option that is accepted and does nothing is worse than one that is refused.
+- **A blocking host call cannot be interrupted.** The run's wall budget is enforced between bytecode operations, so while an embedding or `ctx.fetch` request is in flight the deadline cannot be noticed - the budget ends the run once the call returns. Host calls are bounded by giving them timeouts that already fit the remaining budget (connect **and** read together), not by preemption. For a hard latency ceiling, catch the error and have a fallback path.
 - `ctx.fetch(url, {method, headers, body})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
 - `ctx.env.<NAME>` - secrets for THIS project only, from two merged sources: the project's own secrets set over the API (see "Project secrets") and the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). A host variable wins over a stored secret of the same name. Never another project's, and never the runner's own configuration.
 - `ctx.log(...)` - captured into the run's `console`, bounded.

File diff suppressed because it is too large
+ 617 - 159
api/openapi.json


+ 0 - 1
runner/config/runner.json

@@ -15,7 +15,6 @@
     "max_http_wall_time_ms": 15000,
     "max_job_wall_time_ms": 120000,
     "default_wall_time_ms": 2000,
-    "project_budget_ttl_sec": 15,
     "max_stack_bytes": 524288,
     "bytecode_cache_entries": 64,
     "job_pool_size": 4

+ 67 - 10
runner/src/host_context.cpp

@@ -7,6 +7,7 @@
 #include "embeddings.hpp"
 #include "errors.hpp"
 #include "filters.hpp"
+#include "functions/embed_budget.hpp"
 #include "functions/timezone.hpp"
 #include "outbound_http.hpp"
 #include "principal.hpp"
@@ -16,6 +17,8 @@
 #include "settings_store.hpp"
 #include "vector_search.hpp"
 
+#include <spdlog/spdlog.h>
+
 // Generated from runner/src/host_prelude.js at configure time. The .js file is
 // the editable copy; nothing reads it at runtime, so the binary has no file
 // dependency and a deployed runner cannot be made to execute a different
@@ -511,6 +514,23 @@ int64_t outboundTimeoutMs(int64_t deadline_ms, int64_t elapsed_ms, int64_t reque
     return budget;
 }
 
+/// The `embedTimeoutMs` a search or store asked for, or 0 for "unstated".
+///
+/// Validated rather than coerced: a non-integer or non-positive value is a
+/// script bug, and silently treating it as 0 would mean the author believes a
+/// bound is in force when none is. That failure mode is exactly how this
+/// option went unnoticed in the first place - it was accepted and ignored for a
+/// whole release because nothing complained.
+int64_t embedTimeoutFrom(const nlohmann::json& payload) {
+    if (!payload.is_object()) return 0;
+    const auto it = payload.find("embedTimeoutMs");
+    if (it == payload.end() || it->is_null()) return 0;
+    if (!it->is_number_integer() || it->get<int64_t>() <= 0)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "embedTimeoutMs must be a positive integer number of milliseconds");
+    return it->get<int64_t>();
+}
+
 /// Where ctx.fetch is allowed to connect, and to which address.
 ///
 /// `resolve` is injected so the two rules that matter - classify EVERY address,
@@ -981,7 +1001,8 @@ struct HostContext::Impl {
     /// Embed `text` for a vector op. Mirrors handlers/vectors.cpp: the same
     /// cache, keyed the same way, so a function and an HTTP call that embed the
     /// same string cost one provider call between them.
-    std::vector<float> embed(const CollectionMeta& m, const std::string& text) {
+    std::vector<float> embed(const CollectionMeta& m, const std::string& text,
+                             int64_t callTimeoutMs) {
         loadSettings();
         ResolvedEmbedding cfg =
             resolveEmbedding(global, projectEmbedding ? &*projectEmbedding : nullptr, m);
@@ -990,19 +1011,54 @@ struct HostContext::Impl {
         if (auto hit = embeddingCache().get(key)) return *hit;
 
         // The provider call is outbound work, so it answers to the run's budget
-        // like ctx.fetch does. Seconds, because that is the client's unit.
+        // like ctx.fetch does.
         const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), 0);
         if (budget <= 0)
             throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
                            "the run's time budget is exhausted; not calling the embedding provider");
-        const uint32_t readSec = std::min<uint32_t>(
-            global.embeddingReadTimeoutSec, static_cast<uint32_t>((budget + 999) / 1000));
 
-        EmbeddingClient emb(cfg.apiBase, cfg.apiKey, global.embeddingConnectTimeoutSec,
-                            std::max<uint32_t>(readSec, 1), global.embeddingClientPoolSize);
-        std::vector<float> v = emb.embed(cfg.model, text);
-        embeddingCache().put(key, v);
-        return v;
+        // BOTH timeouts come from the split, and that is the fix for a real
+        // overrun: a 10 s-budget run took 14314 ms because only the read
+        // timeout was clamped to the budget while connect kept its configured
+        // 10 s, and the two are additive. A blocking host call cannot be
+        // interrupted mid-flight, so timeouts that already fit the budget are
+        // the only enforcement there is.
+        functions::EmbedBudgetRequest want;
+        want.remainingBudgetMs = budget;
+        // From the RESOLVED config, so a project's own (narrowing-only)
+        // timeouts apply. Reading the global values here was the bug that made
+        // a per-project timeout impossible to honour.
+        want.configuredConnectSec = cfg.connectTimeoutSec;
+        want.configuredReadSec = cfg.readTimeoutSec;
+        want.callTimeoutMs = callTimeoutMs;
+        const functions::EmbedBudget slice = functions::resolveEmbedBudget(want);
+
+        EmbeddingClient emb(cfg.apiBase, cfg.apiKey, static_cast<uint32_t>(slice.connectSec),
+                            static_cast<uint32_t>(slice.readSec), global.embeddingClientPoolSize);
+        try {
+            std::vector<float> v = emb.embed(cfg.model, text);
+            embeddingCache().put(key, v);
+            return v;
+        } catch (const std::exception& e) {
+            // Leave an operator trace. Before this, a provider that could not
+            // be reached was visible ONLY to the tenant, as an exception inside
+            // their function - the operator's journal said nothing at all,
+            // which is exactly the wrong way round. The origin and the budget
+            // are both here because "unreachable" and "we allowed it 1 second"
+            // are very different diagnoses.
+            spdlog::warn("embedding call to {} failed after connect<={}s read<={}s "
+                         "(project {}, model {}) - {}",
+                         cfg.apiBase.empty() ? "the default provider" : cfg.apiBase,
+                         slice.connectSec, slice.readSec, config.project, cfg.model, e.what());
+            // A timeout the SCRIPT asked for is reported as its own choice, so
+            // an author can branch on it without parsing text. Anything else
+            // keeps the provider's own classification.
+            if (slice.boundByCall)
+                throw ApiError(ErrCode::GatewayTimeout, "embedding_timeout",
+                               "the embedding call exceeded the embedTimeoutMs this call asked "
+                               "for (" + std::to_string(callTimeoutMs) + "ms)");
+            throw;
+        }
     }
 
     /// The query vector for a search or a store, from `vecField` or `textField`.
@@ -1013,7 +1069,8 @@ struct HostContext::Impl {
         if (payload.contains(vecField) && payload.at(vecField).is_array()) {
             v = payload.at(vecField).get<std::vector<float>>();
         } else if (payload.contains(textField) && payload.at(textField).is_string()) {
-            v = embed(m, payload.at(textField).get<std::string>());
+            v = embed(m, payload.at(textField).get<std::string>(),
+                      hostdetail::embedTimeoutFrom(payload));
         } else {
             throw ApiError(ErrCode::Unprocessable, "validation",
                            std::string("provide '") + vecField + "' or '" + textField + "'");

+ 35 - 53
runner/src/main.cpp

@@ -124,7 +124,6 @@ struct RunnerConfig {
     /// Not subscribed to, unlike the server's settings: one read per project
     /// per interval is nothing, and a per-run read would put two round trips on
     /// the hot path for a number that changes by hand.
-    int projectBudgetTtlSec = 15;
     size_t maxStackBytes = 512u * 1024;
     size_t bytecodeCacheEntries = 64;
     /// Runtimes reserved for job runs. A separate lane, so a cron job holding a
@@ -179,7 +178,6 @@ struct RunnerConfig {
             c.maxWallTimeMs = r.value("max_http_wall_time_ms", c.maxWallTimeMs);
             c.maxJobWallTimeMs = r.value("max_job_wall_time_ms", c.maxJobWallTimeMs);
             c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs);
-            c.projectBudgetTtlSec = r.value("project_budget_ttl_sec", c.projectBudgetTtlSec);
             c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes);
             c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries);
             c.jobPoolSize = r.value("job_pool_size", c.jobPoolSize);
@@ -196,63 +194,46 @@ struct RunnerConfig {
     }
 };
 
-/// One project's admin-set wall-time maximum, cached for a few seconds.
+/// One project's admin-set wall-time maximums, per run kind.
 ///
-/// Read straight through the gateway rather than through SettingsStore, for the
-/// reason HostContext gives for doing the same: the store's bootstrap() WRITES,
-/// seeding the settings document, which a runner must never do to configuration
-/// it is only reading. The precedence itself stays in the one pure
-/// maxFunctionWallTimeMsFor().
-class ProjectWallMaxCache {
+/// Backed by SettingsStore, which SUBSCRIBES: a change to a project's cap
+/// reaches the next run immediately instead of after a TTL. This used to be a
+/// hand-rolled cache polling the settings document every
+/// `project_budget_ttl_sec` seconds, which meant clearing a cap appeared not to
+/// work for up to 15 seconds and produced a bug report that cost real time to
+/// run down. The server already hot-reloads the same document off the same
+/// stream; there was no reason for the runner to be the one component guessing.
+///
+/// reloadAll() rather than bootstrap(): bootstrap WRITES, seeding the settings
+/// document, and a runner must never author configuration it only reads.
+/// The precedence itself stays in the one pure maxFunctionWallTimeMsFor().
+class ProjectWallMax {
 public:
-    ProjectWallMaxCache(svapi::DbGateway& db, int ttlSec)
-        : db_(db), ttl_(std::chrono::seconds(ttlSec < 1 ? 1 : ttlSec)) {}
-
-    int64_t get(const std::string& project) {
-        const auto now = std::chrono::steady_clock::now();
-        {
-            std::lock_guard<std::mutex> lock(mu_);
-            auto it = entries_.find(project);
-            if (it != entries_.end() && now < it->second.expires) return it->second.valueMs;
+    explicit ProjectWallMax(svapi::DbGateway& db)
+        : store_(db, svapi::kSettingsCollection, "current") {
+        try {
+            store_.reloadAll();
+        } catch (const std::exception& e) {
+            // Start anyway. An unreadable settings document means no project
+            // cap is known, and a run then falls back to the configured
+            // ceiling, which still bounds it - a project maximum can only
+            // narrow. Refusing to start would be a worse trade.
+            spdlog::warn("could not load project settings at startup - {}", e.what());
         }
-
-        int64_t valueMs = 0;
-        bool read = false;
         try {
-            const std::string coll = svapi::qualify("default", svapi::kSettingsCollection);
-            if (auto doc = db_.client().get(coll, svapi::projectSettingsDocId(project))) {
-                const svapi::ProjectSettings p = svapi::ProjectSettings::fromJson(*doc);
-                valueMs = svapi::maxFunctionWallTimeMsFor(&p);
-            }
-            read = true;
+            store_.startWatch();
         } catch (const std::exception& e) {
-            // A failed read must not silently remove a project's cap, so the
-            // last known value is kept and only its expiry is pushed out. With
-            // nothing known yet the run falls back to the configured ceiling,
-            // which still bounds it - the project maximum can only narrow.
-            spdlog::warn("could not read the wall-time maximum for project {} - {}", project,
-                         e.what());
+            spdlog::warn("could not subscribe to project settings - {}", e.what());
         }
+    }
 
-        std::lock_guard<std::mutex> lock(mu_);
-        auto it = entries_.find(project);
-        if (!read && it != entries_.end()) {
-            it->second.expires = now + ttl_;
-            return it->second.valueMs;
-        }
-        entries_[project] = Entry{valueMs, now + ttl_};
-        return valueMs;
+    int64_t get(const std::string& project, svapi::functions::RunKind kind) const {
+        const std::shared_ptr<const svapi::ProjectSettings> p = store_.projectSnapshot(project);
+        return svapi::maxFunctionWallTimeMsFor(p.get(), kind);
     }
 
 private:
-    struct Entry {
-        int64_t valueMs = 0;
-        std::chrono::steady_clock::time_point expires{};
-    };
-    svapi::DbGateway& db_;
-    std::chrono::steady_clock::duration ttl_;
-    std::mutex mu_;
-    std::map<std::string, Entry> entries_;
+    mutable svapi::SettingsStore store_;
 };
 
 /// RunService's registry seam, over the real FunctionRegistry.
@@ -415,7 +396,7 @@ private:
 
 class RegistryFunctionSource : public svapi::runner::FunctionSource {
 public:
-    RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMaxCache& budgets)
+    RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMax& budgets)
         : registry_(registry), budgets_(budgets) {}
 
     svapi::runner::FunctionView lookup(const std::string& project,
@@ -440,13 +421,14 @@ public:
         view.enabled = row->enabled;
         view.valid = row->valid;
         view.lastError = row->lastError;
-        view.projectMaxWallTimeMs = budgets_.get(project);
+        view.projectMaxWallTimeHttpMs = budgets_.get(project, svapi::functions::RunKind::Http);
+        view.projectMaxWallTimeJobMs = budgets_.get(project, svapi::functions::RunKind::Job);
         return view;
     }
 
 private:
     svapi::FunctionRegistry& registry_;
-    ProjectWallMaxCache& budgets_;
+    ProjectWallMax& budgets_;
 };
 
 /// RunService's ctx seam, over the real HostContext.
@@ -577,7 +559,7 @@ int main(int argc, char** argv) {
     options.version = svapi::VERSION;
     options.jobPoolSize = cfg.jobPoolSize;
 
-    ProjectWallMaxCache projectBudgets(db, cfg.projectBudgetTtlSec);
+    ProjectWallMax projectBudgets(db);
     RegistryFunctionSource source(registry, projectBudgets);
     // The queue has to exist before the bindings that enqueue into it. ensure()
     // is idempotent and also re-opens the collection, without which find()

+ 2 - 1
runner/src/run_service.cpp

@@ -233,7 +233,8 @@ ProtocolResponse RunService::run(const nlohmann::json& request, functions::RunKi
         fn.descriptor.at("timeoutMs").is_number_integer())
         budgetRequest.declaredMs = fn.descriptor.at("timeoutMs").get<int64_t>();
     budgetRequest.defaultMs = options_.defaultTimeoutMs;
-    budgetRequest.projectMaxMs = fn.projectMaxWallTimeMs;
+    budgetRequest.projectMaxMs = kind == functions::RunKind::Job ? fn.projectMaxWallTimeJobMs
+                                                                 : fn.projectMaxWallTimeHttpMs;
     budgetRequest.httpCeilingMs = options_.httpWallCeilingMs;
     budgetRequest.jobCeilingMs = options_.jobWallCeilingMs;
     budgetRequest.hardCeilingMs = options_.limits.wall_time_ms;

+ 9 - 4
runner/src/run_service.hpp

@@ -56,14 +56,19 @@ struct FunctionView {
     /// Why `valid` is false, surfaced in the refusal so the caller does not have
     /// to re-read the registry to find out.
     std::string lastError;
-    /// The project's admin-set wall-time maximum, 0 when it has none.
+    /// The project's admin-set wall-time maximums, 0 when it has none.
     ///
-    /// It arrives through this seam rather than being read here because the
+    /// BOTH kinds, because lookup() does not know how this run was triggered -
+    /// only RunService::run does, and it selects. Resolving a single number
+    /// here would mean the seam deciding a policy question it has no input for.
+    ///
+    /// They arrive through this seam rather than being read here because the
     /// project's settings live in the database, and the whole point of
     /// FunctionSource is that this layer never learns that. The adapter that
     /// already reads the registry row is the one place that can read the
-    /// project's maximum at the same time.
-    int64_t projectMaxWallTimeMs = 0;
+    /// project's maximums at the same time.
+    int64_t projectMaxWallTimeHttpMs = 0;
+    int64_t projectMaxWallTimeJobMs = 0;
 };
 
 /// Where functions come from. Wrapped around FunctionRegistry in production;

+ 3 - 1
runner/tests/run_service_test.cpp

@@ -706,7 +706,9 @@ TEST(RunServiceBudget, AJobCeilingIsNotKilledByTheEnginesHardLimit) {
 TEST(RunServiceBudget, TheProjectMaximumFromTheRegistrySeamApplies) {
     FunctionView v =
         httpFunction("export default function () { return { body: 'ok' }; }", 120000);
-    v.projectMaxWallTimeMs = 4000;
+    // Job run below, so the JOB cap is the one that must apply. Setting only
+    // this proves the two are selected independently.
+    v.projectMaxWallTimeJobMs = 4000;
     FakeSource src;
     src.put("p", "f", v);
     RunServiceOptions o;

+ 91 - 0
src/functions/embed_budget.hpp

@@ -0,0 +1,91 @@
+#pragma once
+#include <algorithm>
+#include <cstdint>
+
+/// How long an embedding call made from inside a function may take.
+///
+/// This exists because a blocking host call cannot be interrupted. The run's
+/// wall budget is enforced by a QuickJS interrupt handler that fires between
+/// bytecode operations, so while a C++ HTTP request is in flight the engine
+/// never regains control and the deadline cannot be noticed. The budget ends
+/// the run only once the call returns. The only way to bound a host call is
+/// therefore to hand the HTTP client timeouts that already fit the budget -
+/// which makes this split the enforcement, not an optimisation.
+///
+/// It got written after a 10 s-budget run took 14314 ms: the READ timeout was
+/// clamped to the remaining budget but the CONNECT timeout was not, and the two
+/// are independent and additive, so a connect stall burned the full
+/// `embedding_connect_timeout_sec` (10 s by default) outside the budget before
+/// the read phase even began. On an endpoint answering a live phone call that
+/// is a hang-up.
+///
+/// Header-only and pure: no clock, no sockets, no settings. Unit-test the
+/// arithmetic here rather than through a provider that has to be unreachable.
+namespace svapi::functions {
+
+/// Everything with a say in one embedding call's timeouts. Milliseconds in,
+/// seconds out, because that is what the HTTP client takes.
+struct EmbedBudgetRequest {
+    /// What is left of the run's wall budget. 0 or less means none, and the
+    /// caller must refuse the call rather than make it with a floor applied.
+    int64_t remainingBudgetMs = 0;
+    /// The operator's configured timeouts, in seconds. 0 means "not stated".
+    int64_t configuredConnectSec = 0;
+    int64_t configuredReadSec = 0;
+    /// A per-call bound from the script (`embedTimeoutMs`). 0 means none.
+    /// Narrowing only: it can ask for less than the budget, never more.
+    int64_t callTimeoutMs = 0;
+};
+
+struct EmbedBudget {
+    /// What to give the HTTP client. Both are at least 1, because the client
+    /// treats 0 as "no timeout" and an unbounded host call is the bug.
+    int64_t connectSec = 1;
+    int64_t readSec = 1;
+    /// True when the script's own `embedTimeoutMs` was the binding constraint,
+    /// so a timeout can be reported as the script's choice rather than as the
+    /// run running out of time. The two want different error codes.
+    bool boundByCall = false;
+};
+
+/// Split the available time between connecting and reading.
+///
+/// Guarantees `connectSec + readSec` does not exceed the available time,
+/// whenever that time is at least 2 seconds. Below that the 1-second floor on
+/// each phase dominates and the worst case is 2 seconds total - still bounded,
+/// and far better than a connect timeout that ignored the budget entirely, but
+/// stated here rather than glossed over: a sub-2-second budget can overrun by
+/// up to a second.
+///
+/// Connect gets at most HALF the available time. A reachable provider connects
+/// in well under a second, so a large connect allowance buys nothing and only
+/// starves the read phase, which is where a slow-but-working provider spends
+/// its time.
+inline EmbedBudget resolveEmbedBudget(const EmbedBudgetRequest& in) {
+    EmbedBudget out;
+
+    int64_t availableMs = in.remainingBudgetMs > 0 ? in.remainingBudgetMs : 0;
+    if (in.callTimeoutMs > 0 && in.callTimeoutMs < availableMs) {
+        availableMs = in.callTimeoutMs;
+        out.boundByCall = true;
+    }
+
+    // Round UP: a 1500 ms budget should allow a 2-second total rather than
+    // being truncated to 1, which would cut a call that had time left.
+    int64_t availableSec = (availableMs + 999) / 1000;
+    if (availableSec < 1) availableSec = 1;
+
+    const int64_t connectCap = std::max<int64_t>(1, availableSec / 2);
+    out.connectSec = in.configuredConnectSec > 0
+                         ? std::min(in.configuredConnectSec, connectCap)
+                         : connectCap;
+    if (out.connectSec < 1) out.connectSec = 1;
+
+    const int64_t readRoom = std::max<int64_t>(1, availableSec - out.connectSec);
+    out.readSec = in.configuredReadSec > 0 ? std::min(in.configuredReadSec, readRoom) : readRoom;
+    if (out.readSec < 1) out.readSec = 1;
+
+    return out;
+}
+
+} // namespace svapi::functions

+ 39 - 22
src/handlers/collections.cpp

@@ -9,12 +9,14 @@ namespace {
 
 // Drop a collection AND the index declarations attached to its name.
 //
-// dropCollection() removes the documents and the collection's metadata but
-// leaves its declared indexes behind, including unique ones. A later collection
-// created under the same name therefore inherits constraints nobody asked for:
-// a write that should succeed is refused as a duplicate, and a unique index the
-// new owner declares reports already_existed instead of validating their data.
-// Undeclaring first is the only way to make a name reusable.
+// Before database 2.12.2, dropCollection() removed the documents and the
+// collection's metadata but left its declared indexes behind, unique ones
+// included. A later collection created under the same name then inherited
+// constraints nobody asked for: a write that should succeed refused as a
+// duplicate, and a unique index the new owner declares reporting
+// already_existed instead of validating their data. 2.12.2 undeclares them
+// itself, but we still undeclare explicitly - it is what makes this correct
+// against an older database, and it is idempotent against a newer one.
 void dropCollectionAndIndexes(DbGateway& db, const std::string& qc) {
     for (const auto& idx : db.client().listIndexes(qc))
         db.client().dropIndex(qc, idx.field);
@@ -23,6 +25,22 @@ void dropCollectionAndIndexes(DbGateway& db, const std::string& qc) {
     db.client().dropCollection(qc);
 }
 
+// Is anything at all still attached to this collection name?
+//
+// A name can be POISONED: the collection itself is gone, so getCollectionInfo
+// answers absent, while its index declarations survive. Gating the repair on
+// the collection's existence therefore skips it in exactly the case that needs
+// it - measured against 2.12.0 data carried into 2.12.2, where a fresh
+// createCollection inherited a stale unique index and the new owner's second
+// write was refused with "unique constraint violated". The upgrade does not
+// retroactively clean old declarations, so any name deleted before this fix is
+// still carrying them and only a create-time repair reaches it.
+bool anythingAttachedTo(DbGateway& db, const std::string& qc) {
+    if (db.client().getCollectionInfo(qc)) return true;
+    if (!db.client().listIndexes(qc).empty()) return true;
+    return !db.client().listCompositeUniqueIndexes(qc).empty();
+}
+
 } // namespace
 
 void registerCollectionRoutes(ApiServer& s) {
@@ -46,10 +64,12 @@ void registerCollectionRoutes(ApiServer& s) {
             model = body.value("embedding_model", "");
         }
         if (d->registry.get(project, name)) throw ApiError(ErrCode::Unprocessable, "exists", "collection already exists");
-        // Drop any stale DB-layer collection (e.g. left from a prior dropProject that didn't
-        // fully clean up its data - DB v2.3.1 Stage F caveat), indexes included,
-        // so the new collection starts with no inherited constraints.
-        if (d->db.client().getCollectionInfo(qualify(project, name)))
+        // Drop whatever is still attached to this name - a stale collection left
+        // by a prior dropProject that did not purge its data, AND any surviving
+        // index declarations even when the collection itself is gone. The
+        // second case is the one a presence check misses, and it is the one
+        // that silently hands the new owner someone else's unique constraint.
+        if (anythingAttachedTo(d->db, qualify(project, name)))
             dropCollectionAndIndexes(d->db, qualify(project, name));
         if (!d->db.client().createCollection(qualify(project, name), 0, false, 0, dim))
             throw ApiError(ErrCode::Unavailable, "db_error", "failed to create collection");
@@ -130,18 +150,15 @@ void registerCollectionRoutes(ApiServer& s) {
         requireProjectManage(k, project);
         if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
         const std::string qc = qualify(project, name);
-        // dropCollection() clears the collection's metadata but does NOT purge the
-        // underlying (vector) index - orphan rows survive and leak into a later
-        // same-name collection (search returns them even though document_count is 0).
-        // remove() per id DOES purge the index, so delete every document first, then
-        // drop the now-empty collection. (See docs/bugs/2026-06-02-collection-delete-leaks-vectors.md)
-        smartbotic::database::Client::QueryOptions opts; opts.limit = 1000000;
-        auto docs = d->db.client().find(qc, opts);
-        for (const auto& doc : docs) {
-            std::string id = doc.value("_id", std::string());
-            if (id.empty()) id = doc.value("id", std::string());
-            if (!id.empty()) d->db.client().remove(qc, id);
-        }
+        // One call, not a per-document sweep. This used to find(limit 1000000)
+        // and remove() every document first, because dropCollection was once
+        // reported to leave the vector index behind so orphan rows leaked into
+        // a later same-name collection. That is no longer true: a drop then a
+        // same-name recreate then a similarity search returns zero hits on
+        // 2.12.0 and 2.12.2 alike, so the workaround cost one round trip per
+        // document for nothing. Verified on both versions before removing it,
+        // because being wrong here means a search serving the previous
+        // tenant's vectors.
         dropCollectionAndIndexes(d->db, qc);
         d->registry.remove(project, name);
         sendJson(res, 200, {{"deleted", name}});

+ 94 - 17
src/handlers/project_settings.cpp

@@ -26,6 +26,31 @@ void applyOverride(const nlohmann::json& body, const char* name, std::string& fi
     field = s;
 }
 
+/// A seconds override, or null when the project inherits. Kept as its own
+/// helper so the three places that render it cannot drift.
+nlohmann::json secsOrNull(const std::optional<uint32_t>& v) {
+    return (v && *v > 0) ? nlohmann::json(*v) : nlohmann::json(nullptr);
+}
+
+/// Read a narrowing timeout override out of a PUT body, in place.
+///
+/// null clears it, the same "inherit again" convention the endpoint fields use.
+/// A value ABOVE the global is accepted and stored rather than refused: the
+/// effective value is min(project, global), so storing it is harmless and
+/// refusing it would make a project's config invalid the moment an operator
+/// LOWERED the global one.
+void applyTimeoutOverride(const nlohmann::json& body, const char* name,
+                          std::optional<uint32_t>& field) {
+    if (!body.contains(name)) return;
+    const nlohmann::json& v = body.at(name);
+    if (v.is_null()) { field.reset(); return; }
+    if (!v.is_number_integer() || v.get<long long>() <= 0)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(name) + " must be a positive integer number of seconds, "
+                                           "or null to inherit the global value");
+    field = v.get<uint32_t>();
+}
+
 nlohmann::json viewJson(const Settings& global, const ProjectSettings* p) {
     // An empty CollectionMeta means "no per-collection model pin", so this shows
     // what a collection without its own model would resolve to.
@@ -34,15 +59,23 @@ nlohmann::json viewJson(const Settings& global, const ProjectSettings* p) {
     return {{"effective",
              {{"openai_api_base", eff.apiBase},
               {"default_embedding_model", eff.model},
-              {"openai_api_key_set", !eff.apiKey.empty()}}},
+              {"openai_api_key_set", !eff.apiKey.empty()},
+              {"embedding_connect_timeout_sec", eff.connectTimeoutSec},
+              {"embedding_read_timeout_sec", eff.readTimeoutSec}}},
             {"inherited",
              {{"openai_api_base", global.openaiApiBase},
               {"default_embedding_model", global.defaultEmbeddingModel},
-              {"openai_api_key_set", !global.openaiApiKey.empty()}}},
+              {"openai_api_key_set", !global.openaiApiKey.empty()},
+              {"embedding_connect_timeout_sec", global.embeddingConnectTimeoutSec},
+              {"embedding_read_timeout_sec", global.embeddingReadTimeoutSec}}},
             {"overrides",
              {{"openai_api_base", p ? p->openaiApiBase : ""},
               {"default_embedding_model", p ? p->defaultEmbeddingModel : ""},
-              {"openai_api_key_set", p && !p->openaiApiKey.empty()}}}};
+              {"openai_api_key_set", p && !p->openaiApiKey.empty()},
+              {"embedding_connect_timeout_sec",
+               p ? secsOrNull(p->embeddingConnectTimeoutSec) : nlohmann::json(nullptr)},
+              {"embedding_read_timeout_sec",
+               p ? secsOrNull(p->embeddingReadTimeoutSec) : nlohmann::json(nullptr)}}}};
 }
 
 /// The function-budget view. Separate from the embedding view because the two
@@ -50,12 +83,32 @@ nlohmann::json viewJson(const Settings& global, const ProjectSettings* p) {
 /// admin-only, and mixing them into one document would mean a project manager
 /// reading a field he cannot set - or, worse, a later edit letting him set it.
 nlohmann::json budgetJson(const ProjectSettings* p) {
-    nlohmann::json j;
-    const int64_t maxMs = maxFunctionWallTimeMsFor(p);
-    // Null rather than 0: "no project maximum" and "a maximum of zero" are
-    // different answers, and 0 renders as the second one.
-    j["max_wall_time_ms"] = maxMs > 0 ? nlohmann::json(maxMs) : nlohmann::json(nullptr);
-    return j;
+    const int64_t httpMs = maxFunctionWallTimeMsFor(p, functions::RunKind::Http);
+    const int64_t jobMs  = maxFunctionWallTimeMsFor(p, functions::RunKind::Job);
+    // Null rather than 0 for an unset kind: "no project maximum" and "a maximum
+    // of zero" are different answers, and 0 renders as the second one.
+    //
+    // An OBJECT rather than the bare number this returned before 0.6.0. A bare
+    // number cannot express "10 s for routes, 60 s for jobs", and leaving it in
+    // place alongside the per-kind values would mean a client reading only the
+    // old key sees null - "no cap" - while a cap is in force. Being told the
+    // shape changed is better than being told the wrong answer.
+    return {{"max_wall_time_ms",
+             {{"http", httpMs > 0 ? nlohmann::json(httpMs) : nlohmann::json(nullptr)},
+              {"job", jobMs > 0 ? nlohmann::json(jobMs) : nlohmann::json(nullptr)}}}};
+}
+
+/// Read one kind's cap out of a PUT body value. Returns nullopt for "clear it".
+///
+/// Throws on anything else, rather than ignoring it: a typo in an admin-only
+/// limit must not look like it applied.
+std::optional<int64_t> capFromJson(const nlohmann::json& v, const char* what) {
+    if (v.is_null()) return std::nullopt;
+    if (!v.is_number_integer() || v.get<long long>() <= 0)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(what) + " must be a positive integer, or null to "
+                                           "inherit the runner's ceiling");
+    return v.get<int64_t>();
 }
 
 }  // namespace
@@ -85,6 +138,9 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         applyOverride(body, "openai_api_base", updated.openaiApiBase);
         applyOverride(body, "openai_api_key", updated.openaiApiKey);
         applyOverride(body, "default_embedding_model", updated.defaultEmbeddingModel);
+        applyTimeoutOverride(body, "embedding_connect_timeout_sec",
+                             updated.embeddingConnectTimeoutSec);
+        applyTimeoutOverride(body, "embedding_read_timeout_sec", updated.embeddingReadTimeoutSec);
 
         if (!updated.openaiApiBase.empty() &&
             updated.openaiApiBase.rfind("http://", 0) != 0 &&
@@ -134,14 +190,28 @@ void registerProjectSettingsRoutes(ApiServer& s) {
 
         if (body.contains("max_wall_time_ms")) {
             const nlohmann::json& v = body["max_wall_time_ms"];
-            // null clears the cap, the same "inherit again" convention the
-            // embedding overrides use.
-            if (v.is_null()) updated.maxFunctionWallTimeMs.reset();
-            else if (!v.is_number_integer() || v.get<long long>() <= 0)
-                throw ApiError(ErrCode::Unprocessable, "validation",
-                               "max_wall_time_ms must be a positive integer, or null to "
-                               "inherit the runner's ceiling");
-            else updated.maxFunctionWallTimeMs = v.get<int64_t>();
+            if (v.is_object()) {
+                // Per-kind. A key that is absent LEAVES that kind alone, so a
+                // caller can narrow routes without touching jobs; null clears.
+                if (v.contains("http"))
+                    updated.maxFunctionWallTimeHttpMs =
+                        capFromJson(v.at("http"), "max_wall_time_ms.http");
+                if (v.contains("job"))
+                    updated.maxFunctionWallTimeJobMs =
+                        capFromJson(v.at("job"), "max_wall_time_ms.job");
+                for (auto it = v.begin(); it != v.end(); ++it)
+                    if (it.key() != "http" && it.key() != "job")
+                        throw ApiError(ErrCode::Unprocessable, "validation",
+                                       "max_wall_time_ms accepts only 'http' and 'job'; got '" +
+                                           it.key() + "'");
+            } else {
+                // The pre-0.6.0 spelling, still honoured: a bare integer sets
+                // BOTH kinds, and null clears both. Keeping it working means an
+                // existing caller does not have to change to keep its cap.
+                const std::optional<int64_t> both = capFromJson(v, "max_wall_time_ms");
+                updated.maxFunctionWallTimeHttpMs = both;
+                updated.maxFunctionWallTimeJobMs = both;
+            }
         }
 
         if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
@@ -173,6 +243,13 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         updated.openaiApiBase.clear();
         updated.openaiApiKey.clear();
         updated.defaultEmbeddingModel.clear();
+        // The timeout overrides are embedding overrides too, so "revert my
+        // embedding override" must clear them. Leaving them would make this
+        // route's own hasEmbeddingOverrides() still true afterwards, so the
+        // next call would report there was something to revert when there was
+        // not.
+        updated.embeddingConnectTimeoutSec.reset();
+        updated.embeddingReadTimeoutSec.reset();
         // Only now is dropping the document right: nothing else is stored in it.
         if (!updated.hasAnyOverrides()) {
             d->settings.removeProject(project);

+ 7 - 3
src/handlers/vectors.cpp

@@ -65,9 +65,13 @@ std::vector<float> resolveVector(ServerDeps* d, const std::string& project,
         if (hit) {
             v = std::move(*hit);
         } else {
-            EmbeddingClient emb(cfg.apiBase, cfg.apiKey,
-                                snap->embeddingConnectTimeoutSec, snap->embeddingReadTimeoutSec,
-                                snap->embeddingClientPoolSize);
+            // cfg, not snap: the timeouts come from the same resolveEmbedding()
+            // that chose the endpoint, so a project's narrowing override
+            // applies to an HTTP vector call exactly as it does inside a
+            // function. Reading the global snapshot here would have made the
+            // per-project setting work for one caller and not the other.
+            EmbeddingClient emb(cfg.apiBase, cfg.apiKey, cfg.connectTimeoutSec,
+                                cfg.readTimeoutSec, snap->embeddingClientPoolSize);
             v = emb.embed(cfg.model, text);
             if (!noStore) embeddingCache().put(key, v);  // copy, not move: v is still needed for the dimension check below
         }

+ 54 - 8
src/project_settings.cpp

@@ -1,4 +1,5 @@
 #include "project_settings.hpp"
+#include <algorithm>
 #include "collection_registry.hpp"
 #include "function_record.hpp"
 #include "settings.hpp"
@@ -20,9 +21,29 @@ ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
     // Same absent-versus-present distinction, and the same reason: a stored
     // value survives a change to the runner's default ceiling, an absent key
     // follows it.
+    //
+    // The bare key is the pre-0.6.0 spelling and meant "both kinds", so it
+    // seeds both. The per-kind keys are read afterwards and win, which is what
+    // lets a document written by a newer server still be understood when only
+    // one kind is capped.
+    if (j.contains("embedding_connect_timeout_sec") &&
+        j.at("embedding_connect_timeout_sec").is_number_integer())
+        p.embeddingConnectTimeoutSec = j.at("embedding_connect_timeout_sec").get<uint32_t>();
+    if (j.contains("embedding_read_timeout_sec") &&
+        j.at("embedding_read_timeout_sec").is_number_integer())
+        p.embeddingReadTimeoutSec = j.at("embedding_read_timeout_sec").get<uint32_t>();
     if (j.contains("max_function_wall_time_ms") &&
-        j.at("max_function_wall_time_ms").is_number_integer())
-        p.maxFunctionWallTimeMs = j.at("max_function_wall_time_ms").get<int64_t>();
+        j.at("max_function_wall_time_ms").is_number_integer()) {
+        const int64_t both = j.at("max_function_wall_time_ms").get<int64_t>();
+        p.maxFunctionWallTimeHttpMs = both;
+        p.maxFunctionWallTimeJobMs = both;
+    }
+    if (j.contains("max_function_wall_time_http_ms") &&
+        j.at("max_function_wall_time_http_ms").is_number_integer())
+        p.maxFunctionWallTimeHttpMs = j.at("max_function_wall_time_http_ms").get<int64_t>();
+    if (j.contains("max_function_wall_time_job_ms") &&
+        j.at("max_function_wall_time_job_ms").is_number_integer())
+        p.maxFunctionWallTimeJobMs = j.at("max_function_wall_time_job_ms").get<int64_t>();
     return p;
 }
 
@@ -34,7 +55,22 @@ nlohmann::json ProjectSettings::toJson() const {
     // Written only when set, so round-tripping a project that never configured
     // one does not quietly pin today's built-in default into storage.
     if (defaultFunctionPolicy) j["default_function_policy"] = defaultFunctionPolicy->toJson();
-    if (maxFunctionWallTimeMs) j["max_function_wall_time_ms"] = *maxFunctionWallTimeMs;
+    if (embeddingConnectTimeoutSec) j["embedding_connect_timeout_sec"] = *embeddingConnectTimeoutSec;
+    if (embeddingReadTimeoutSec) j["embedding_read_timeout_sec"] = *embeddingReadTimeoutSec;
+    if (maxFunctionWallTimeHttpMs) j["max_function_wall_time_http_ms"] = *maxFunctionWallTimeHttpMs;
+    if (maxFunctionWallTimeJobMs) j["max_function_wall_time_job_ms"] = *maxFunctionWallTimeJobMs;
+    // Also write the pre-0.6.0 bare key, set to the TIGHTER of the two, so a
+    // rollback to an older server still enforces a cap rather than silently
+    // enforcing none. Deliberately the tighter one: a rollback that loosens a
+    // limit an admin set is the failure worth avoiding, and an over-tight job
+    // budget is visible and complained about, where an over-loose one is not.
+    if (maxFunctionWallTimeHttpMs && maxFunctionWallTimeJobMs)
+        j["max_function_wall_time_ms"] =
+            std::min(*maxFunctionWallTimeHttpMs, *maxFunctionWallTimeJobMs);
+    else if (maxFunctionWallTimeHttpMs)
+        j["max_function_wall_time_ms"] = *maxFunctionWallTimeHttpMs;
+    else if (maxFunctionWallTimeJobMs)
+        j["max_function_wall_time_ms"] = *maxFunctionWallTimeJobMs;
     return j;
 }
 
@@ -42,11 +78,19 @@ std::string projectSettingsDocId(const std::string& project) { return "project_"
 
 ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,
                                    const CollectionMeta& coll) {
-    ResolvedEmbedding r{global.openaiApiBase, global.openaiApiKey, global.defaultEmbeddingModel};
+    ResolvedEmbedding r{global.openaiApiBase, global.openaiApiKey, global.defaultEmbeddingModel,
+                        global.embeddingConnectTimeoutSec, global.embeddingReadTimeoutSec};
     if (proj) {
         if (!proj->openaiApiBase.empty())         r.apiBase = proj->openaiApiBase;
         if (!proj->openaiApiKey.empty())          r.apiKey  = proj->openaiApiKey;
         if (!proj->defaultEmbeddingModel.empty()) r.model   = proj->defaultEmbeddingModel;
+        // min(), not "override wins": see the header. A zero override is
+        // "unset" by the same convention the wall-time cap uses, so it is
+        // ignored rather than meaning "no timeout at all".
+        if (proj->embeddingConnectTimeoutSec && *proj->embeddingConnectTimeoutSec > 0)
+            r.connectTimeoutSec = std::min(r.connectTimeoutSec, *proj->embeddingConnectTimeoutSec);
+        if (proj->embeddingReadTimeoutSec && *proj->embeddingReadTimeoutSec > 0)
+            r.readTimeoutSec = std::min(r.readTimeoutSec, *proj->embeddingReadTimeoutSec);
     }
     if (!coll.embeddingModel.empty()) r.model = coll.embeddingModel;
     return r;
@@ -57,10 +101,12 @@ KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj) {
     return builtinDefaultFunctionPolicy();
 }
 
-int64_t maxFunctionWallTimeMsFor(const ProjectSettings* proj) {
-    if (proj && proj->maxFunctionWallTimeMs && *proj->maxFunctionWallTimeMs > 0)
-        return *proj->maxFunctionWallTimeMs;
-    return 0;
+int64_t maxFunctionWallTimeMsFor(const ProjectSettings* proj, functions::RunKind kind) {
+    if (!proj) return 0;
+    const std::optional<int64_t>& v = kind == functions::RunKind::Job
+                                          ? proj->maxFunctionWallTimeJobMs
+                                          : proj->maxFunctionWallTimeHttpMs;
+    return (v && *v > 0) ? *v : 0;
 }
 
 } // namespace svapi

+ 45 - 11
src/project_settings.hpp

@@ -1,4 +1,5 @@
 #pragma once
+#include "functions/wall_budget.hpp"
 #include "apikey.hpp"
 #include <nlohmann/json.hpp>
 #include <cstdint>
@@ -32,19 +33,36 @@ struct ProjectSettings {
     /// retroactively widens or narrows anything already deployed.
     std::optional<KeyScope> defaultFunctionPolicy;
 
-    /// The longest wall time any of this project's functions may be granted,
-    /// in milliseconds. Unset means "whatever the runner's ceiling allows".
+    /// Per-project embedding timeouts, in seconds. Unset inherits the global
+    /// value; set, the effective value is min(this, global), so a project can
+    /// only tighten. They exist because a latency-critical project needs a
+    /// strict connect timeout while another legitimately wants a generous one,
+    /// and the global setting cannot serve both without one of them suffering.
+    std::optional<uint32_t> embeddingConnectTimeoutSec;
+    std::optional<uint32_t> embeddingReadTimeoutSec;
+
+    /// The longest wall time this project's functions may be granted, per run
+    /// kind, in milliseconds. Unset means "whatever the runner's ceiling for
+    /// that kind allows".
+    ///
+    /// Admin-settable and narrowing only: neither can raise a ceiling, only cut
+    /// a project's scripts below one. The cap exists because the job ceiling is
+    /// minutes long, and without it one tenant's `timeoutMs: 120000` holds a
+    /// pooled runtime - a shared resource - for two minutes at a time, which is
+    /// a denial of service against every other project on the runner.
     ///
-    /// Admin-settable and narrowing only: it cannot raise a ceiling, only cut a
-    /// project's scripts below one. It exists because the job ceiling is minutes
-    /// long, and without a per-project cap one tenant's `timeoutMs: 120000`
-    /// holds a pooled runtime - a shared resource - for two minutes at a time,
-    /// which is a denial of service against every other project on the runner.
-    std::optional<int64_t> maxFunctionWallTimeMs;
+    /// Split by kind because a single number cannot serve both. An HTTP run is
+    /// behind a socket somebody is waiting on, so an admin wants it short; a
+    /// job has no client and legitimately needs tens of seconds. With one
+    /// number, capping a project's routes at 10 s also cut its cron work to
+    /// 10 s, so the only safe setting was no cap at all.
+    std::optional<int64_t> maxFunctionWallTimeHttpMs;
+    std::optional<int64_t> maxFunctionWallTimeJobMs;
 
     /// True when at least one EMBEDDING field overrides the global value.
     bool hasEmbeddingOverrides() const {
-        return !openaiApiBase.empty() || !openaiApiKey.empty() || !defaultEmbeddingModel.empty();
+        return !openaiApiBase.empty() || !openaiApiKey.empty() || !defaultEmbeddingModel.empty() ||
+               embeddingConnectTimeoutSec.has_value() || embeddingReadTimeoutSec.has_value();
     }
 
     /// True when the project has anything stored at all. The settings document
@@ -53,7 +71,7 @@ struct ProjectSettings {
     /// function policy the moment someone cleared an embedding override.
     bool hasAnyOverrides() const {
         return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value() ||
-               maxFunctionWallTimeMs.has_value();
+               maxFunctionWallTimeHttpMs.has_value() || maxFunctionWallTimeJobMs.has_value();
     }
 
     /// A project base URL must carry its own API key, otherwise the global
@@ -74,12 +92,24 @@ struct ResolvedEmbedding {
     std::string apiBase;
     std::string apiKey;
     std::string model;
+    /// Effective timeouts, in seconds, already narrowed. Never above the global
+    /// value, so a project cannot lengthen how long it may hold a shared
+    /// provider connection - only shorten it.
+    uint32_t connectTimeoutSec = 0;
+    uint32_t readTimeoutSec = 0;
 };
 
 /// Resolve the effective embedding endpoint for a collection.
 ///   apiBase / apiKey : project override, else global.
 ///   model            : collection pin, else project override, else global default.
+///   timeouts         : min(project override, global) - NARROWING ONLY.
 /// `proj` may be null when the project has no overrides stored.
+///
+/// The timeouts take min() rather than the usual "override wins" because they
+/// govern a shared resource. An override that could RAISE them would let one
+/// tenant hold a provider connection, and with it a pooled runtime, far longer
+/// than the operator allowed - the same reason the function wall-time cap can
+/// only narrow.
 ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings* proj,
                                    const CollectionMeta& coll);
 
@@ -95,6 +125,10 @@ KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj);
 /// stored. A stored value <= 0 is treated as unset rather than as a project
 /// nobody can run a function in, because that is what a fat-fingered 0 means
 /// and the other reading takes a release to notice.
-int64_t maxFunctionWallTimeMsFor(const ProjectSettings* proj);
+/// The project's cap for one kind of run, or 0 for "no project cap".
+///
+/// Takes the kind rather than returning a single number, because the two are
+/// independent: a project may cap HTTP without capping jobs.
+int64_t maxFunctionWallTimeMsFor(const ProjectSettings* proj, functions::RunKind kind);
 
 } // namespace svapi

+ 6 - 1
src/settings_store.cpp

@@ -94,12 +94,17 @@ bool SettingsStore::save(const Settings& s) {
     return true;
 }
 
+void SettingsStore::reloadAll() {
+    reloadFromDb();
+    reloadProjectsFromDb();
+}
+
 void SettingsStore::startWatch() {
     sub_ = db_.client().subscribe(
         {coll_},
         [this](const std::string&, const std::string&,
                const std::string&, const std::optional<nlohmann::json>&) {
-            try { reloadFromDb(); reloadProjectsFromDb(); }
+            try { reloadAll(); }
             catch (const std::exception& e) {
                 spdlog::warn("settings reload failed: {}", e.what());
             }

+ 9 - 0
src/settings_store.hpp

@@ -55,6 +55,15 @@ public:
     /// Returns false when the project had no overrides stored.
     bool removeProject(const std::string& project);
 
+    /// Load both the global document and every project override, without
+    /// writing anything.
+    ///
+    /// Exists for the runner, which must read this configuration and must never
+    /// seed it: bootstrap() WRITES the settings document, so a read-only
+    /// consumer calls this instead. Pair it with startWatch() and the snapshot
+    /// then stays current with no polling.
+    void reloadAll();
+
     /// Subscribe to DB change events so the snapshot stays current automatically.
     void startWatch();
 

+ 6 - 0
tests/CMakeLists.txt

@@ -212,6 +212,12 @@ target_include_directories(test_index_request PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_index_request PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
 gtest_discover_tests(test_index_request)
 
+# Header-only and pure, so it links neither the database client nor httplib.
+add_executable(test_embed_budget test_embed_budget.cpp)
+target_include_directories(test_embed_budget PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_embed_budget PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_embed_budget)
+
 # Document body shaping and the increment deltas: header-only and pure.
 add_executable(test_documents_util test_documents_util.cpp)
 target_include_directories(test_documents_util PRIVATE ${CMAKE_SOURCE_DIR}/src)

+ 75 - 5
tests/test_api_integration.cpp

@@ -737,6 +737,20 @@ TEST_F(ApiFixture, ScopedKeyRateLimited) {
     const std::string ct   = "application/json";
     const std::string path = base + "/rate_coll/documents";
 
+    // The limiter counts within a fixed CALENDAR minute, not a sliding window
+    // (RateLimiter::Window keys on the epoch minute). Three requests that
+    // straddle a minute boundary therefore land in two windows, the count
+    // resets, and the third is allowed - the test fails for a reason that has
+    // nothing to do with rate limiting. So start the burst only when the whole
+    // of it comfortably fits inside the current minute.
+    {
+        using namespace std::chrono;
+        const auto secondsIntoMinute =
+            duration_cast<seconds>(system_clock::now().time_since_epoch()).count() % 60;
+        if (secondsIntoMinute > 56)
+            std::this_thread::sleep_for(seconds(61 - secondsIntoMinute));
+    }
+
     // 1st request → 201
     auto r1 = request("POST", path, jDoc, ct, rkey);
     ASSERT_TRUE(r1);
@@ -1001,11 +1015,13 @@ TEST_F(ApiFixture, IndexValuesRejectsOutOfRangeLimit) {
     ASSERT_TRUE(absent); EXPECT_EQ(absent->status, 200);
 }
 
-// Named "uqdup" rather than "uq": a database run before the index-undeclare
-// fixes left a unique sku index declared on the dead collection
-// svapitest_apiproj:uq, and that declaration cannot be removed through any
-// client call, so the old name reports already_existed forever on a persistent
-// database. See the dropCollection caveat in CLAUDE.md.
+// Named "uqdup" rather than "uq" for a historical reason worth keeping: a run
+// on database 2.12.1 left a unique sku index declared on the dead collection
+// svapitest_apiproj:uq, and on that version no client call could remove it, so
+// the name reported already_existed forever on a persistent database. Database
+// 2.12.2 made dropIndex work on an absent collection and the name has since
+// been repaired, so "uq" would work again - but the rename costs nothing and
+// the next poisoned name will not announce itself either.
 TEST_F(ApiFixture, UniqueIndexRejectsExistingDuplicates) {
     auto c = admin();
     std::string base = "/api/v1/projects/" + project_ + "/collections";
@@ -2309,6 +2325,60 @@ TEST_F(ApiFixture, CompositeIndexDropValidation) {
     EXPECT_EQ(c.Delete((idx + "?fields=nope_a&fields=nope_b").c_str())->status, 200);
 }
 
+// A collection name whose COLLECTION is gone but whose index declarations
+// survive is "poisoned": getCollectionInfo answers absent while listIndexes
+// still names the field. Gating the create-time repair on the collection's
+// existence skips it in exactly that case, and the next owner of the name
+// silently inherits a unique constraint nobody declared - their legitimate
+// write is refused as a duplicate.
+//
+// Constructed here by dropping the collection through the CLIENT, bypassing our
+// own delete handler, which is also how it happens in the wild: any collection
+// deleted before we started undeclaring indexes left this behind. On a database
+// that undeclares on drop (2.12.2+) the poisoned state cannot be built at all
+// and the assertions below simply hold from the start - which is the point, the
+// test asserts the END state rather than the repair mechanism.
+TEST_F(ApiFixture, ARecycledCollectionNameInheritsNoConstraint) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    const std::string ct = "application/json";
+
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","recyc"},{"kind","json"}}.dump(),
+                     ct)->status, 201);
+    ASSERT_EQ(c.Post((base + "/recyc/documents").c_str(),
+                     nlohmann::json{{"sku","OLD"}}.dump(), ct)->status, 201);
+    ASSERT_EQ(c.Post((base + "/recyc/indexes").c_str(),
+                     nlohmann::json{{"field","sku"},{"unique",true}}.dump(), ct)->status, 201);
+
+    // Construct the poisoned state entirely behind the API's back. Going
+    // through DELETE would not do it: our own delete handler undeclares the
+    // indexes, which is the state we are trying to build. So drop the
+    // collection through the client (leaving the declaration attached to the
+    // name) and drop the registry entry directly, which is what a pre-fix
+    // delete, or a dropProject that never purged, left behind.
+    ASSERT_TRUE(db_->client().dropCollection(svapi::qualify(project_, "recyc")));
+    ASSERT_TRUE(registry_->remove(project_, "recyc"));
+
+    // A new owner takes the name and must get a clean collection.
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","recyc"},{"kind","json"}}.dump(),
+                     ct)->status, 201);
+    const std::string docs = base + "/recyc/documents";
+    EXPECT_EQ(c.Post(docs.c_str(), nlohmann::json{{"sku","NEW"}}.dump(), ct)->status, 201);
+    // The second write shares the sku. With an inherited unique index it is a
+    // 409; with none it is an ordinary insert.
+    auto second = c.Post(docs.c_str(), nlohmann::json{{"sku","NEW"}}.dump(), ct);
+    ASSERT_TRUE(second);
+    EXPECT_EQ(second->status, 201) << "inherited a unique constraint from the previous "
+                                      "collection of this name; body: " << second->body;
+    // And declaring it fresh validates the NEW data rather than reporting that
+    // it already existed.
+    auto declared = c.Post((base + "/recyc/indexes").c_str(),
+                           nlohmann::json{{"field","sku"},{"unique",true}}.dump(), ct);
+    ASSERT_TRUE(declared);
+    EXPECT_EQ(declared->status, 409) << "two rows share sku=NEW, so declaring it unique must "
+                                        "be refused; body: " << declared->body;
+}
+
 // --- Atomic increment (database 2.12.0) ------------------------------------
 
 TEST_F(ApiFixture, IncrementAddsAndReturnsNewValues) {

+ 134 - 0
tests/test_embed_budget.cpp

@@ -0,0 +1,134 @@
+#include "functions/embed_budget.hpp"
+#include <gtest/gtest.h>
+
+using svapi::functions::EmbedBudgetRequest;
+using svapi::functions::resolveEmbedBudget;
+
+namespace {
+
+// The regression this file exists for. A 10 s-budget run took 14314 ms because
+// the read timeout was clamped to the remaining budget and the connect timeout
+// was not, so a connect stall spent the full configured 10 s outside the
+// budget and the read phase then spent what was left.
+TEST(EmbedBudget, ConnectPlusReadFitInsideTheRunBudget) {
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    in.configuredConnectSec = 10;  // the default that caused the overrun
+    in.configuredReadSec = 60;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_LE(b.connectSec + b.readSec, 10)
+        << "connect " << b.connectSec << " + read " << b.readSec
+        << " must not exceed the 10 s budget";
+    EXPECT_GE(b.connectSec, 1);
+    EXPECT_GE(b.readSec, 1);
+}
+
+TEST(EmbedBudget, ConnectNeverTakesMoreThanHalf) {
+    // A reachable provider connects in well under a second, so a big connect
+    // allowance only starves the read phase, which is where a slow-but-working
+    // provider actually spends its time.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    in.configuredConnectSec = 60;
+    in.configuredReadSec = 60;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_LE(b.connectSec, 5);
+    EXPECT_GE(b.readSec, 5);
+}
+
+TEST(EmbedBudget, AGenerousBudgetStillHonoursTheConfiguredTimeouts) {
+    // The split must not become its own cap: with 60 s available and a 10 s
+    // connect configured, connect stays 10 rather than being stretched to 30.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 60000;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 10);
+    EXPECT_EQ(b.readSec, 50) << "read gets the rest of the budget, not the full configured 60";
+    EXPECT_LE(b.connectSec + b.readSec, 60);
+}
+
+TEST(EmbedBudget, TheScriptsOwnTimeoutNarrowsButNeverWidens) {
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 60000;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    in.callTimeoutMs = 4000;  // embedTimeoutMs: 4000
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_TRUE(b.boundByCall);
+    EXPECT_LE(b.connectSec + b.readSec, 4);
+
+    // Asking for MORE than the run has left changes nothing: the run's budget
+    // is the hard limit, and a script cannot vote itself extra time.
+    in.callTimeoutMs = 600000;
+    const auto wide = resolveEmbedBudget(in);
+    EXPECT_FALSE(wide.boundByCall);
+    EXPECT_LE(wide.connectSec + wide.readSec, 60);
+}
+
+TEST(EmbedBudget, BoundByCallDistinguishesWhoRanOutOfTime) {
+    // The two want different error codes: one is the script's own choice, the
+    // other is the run running out of budget, and an author debugging a
+    // timeout needs to know which.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 10000;
+    in.configuredConnectSec = 2;
+    in.configuredReadSec = 60;
+    EXPECT_FALSE(resolveEmbedBudget(in).boundByCall);
+    in.callTimeoutMs = 3000;
+    EXPECT_TRUE(resolveEmbedBudget(in).boundByCall);
+    // Equal is not "bound by the call" - nothing was narrowed.
+    in.callTimeoutMs = 10000;
+    EXPECT_FALSE(resolveEmbedBudget(in).boundByCall);
+}
+
+TEST(EmbedBudget, NeitherTimeoutIsEverZero) {
+    // The HTTP client reads 0 as "no timeout", so a zero here is precisely the
+    // unbounded host call this whole file exists to prevent.
+    for (const int64_t ms : {1, 100, 999, 1000, 1001, 2000}) {
+        EmbedBudgetRequest in;
+        in.remainingBudgetMs = ms;
+        in.configuredConnectSec = 10;
+        in.configuredReadSec = 60;
+        const auto b = resolveEmbedBudget(in);
+        EXPECT_GE(b.connectSec, 1) << "at " << ms << "ms";
+        EXPECT_GE(b.readSec, 1) << "at " << ms << "ms";
+    }
+}
+
+TEST(EmbedBudget, ASubTwoSecondBudgetOverrunsByAtMostOneSecond) {
+    // Stated rather than glossed over. The 1-second floor on each phase
+    // dominates below 2 s, so the worst case is 2 s total. Still bounded, and
+    // a world away from a connect timeout that ignored the budget entirely.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 500;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 1);
+    EXPECT_EQ(b.readSec, 1);
+    EXPECT_LE(b.connectSec + b.readSec, 2);
+}
+
+TEST(EmbedBudget, UnconfiguredTimeoutsStillProduceBoundedOnes) {
+    // A half-written settings document must not yield an unbounded call.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 8000;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_GE(b.connectSec, 1);
+    EXPECT_GE(b.readSec, 1);
+    EXPECT_LE(b.connectSec + b.readSec, 8);
+}
+
+TEST(EmbedBudget, RoundsUpSoATimeLeftBudgetIsNotTruncatedToNothing) {
+    // 1500 ms of budget should allow a 2-second total, not be truncated to 1.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 1500;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec + b.readSec, 2);
+}
+
+} // namespace

+ 174 - 17
tests/test_project_settings.cpp

@@ -190,48 +190,205 @@ TEST(ProjectSettings, AnUnsetPolicyIsNotWrittenToStorage) {
     EXPECT_FALSE(p.toJson().contains("default_function_policy"));
 }
 
+// Per-project embedding timeouts. NARROWING ONLY, which is the whole property
+// worth testing: they govern a shared resource, so an override that could raise
+// them would let one tenant hold a provider connection - and the pooled runtime
+// waiting on it - for longer than the operator allowed.
+
+TEST(EmbeddingTimeouts, NoOverrideInheritsTheGlobalValues) {
+    Settings g;
+    g.embeddingConnectTimeoutSec = 10;
+    g.embeddingReadTimeoutSec = 60;
+    const CollectionMeta none;
+    const ResolvedEmbedding r = resolveEmbedding(g, nullptr, none);
+    EXPECT_EQ(r.connectTimeoutSec, 10u);
+    EXPECT_EQ(r.readTimeoutSec, 60u);
+}
+
+TEST(EmbeddingTimeouts, AProjectCanTighten) {
+    Settings g;
+    g.embeddingConnectTimeoutSec = 10;
+    g.embeddingReadTimeoutSec = 60;
+    ProjectSettings p;
+    p.embeddingConnectTimeoutSec = 2;
+    p.embeddingReadTimeoutSec = 4;
+    const CollectionMeta none;
+    const ResolvedEmbedding r = resolveEmbedding(g, &p, none);
+    EXPECT_EQ(r.connectTimeoutSec, 2u);
+    EXPECT_EQ(r.readTimeoutSec, 4u);
+}
+
+TEST(EmbeddingTimeouts, AProjectCannotLoosen) {
+    // The property. A project asking for longer than the global allowance gets
+    // the global allowance, not its own request.
+    Settings g;
+    g.embeddingConnectTimeoutSec = 5;
+    g.embeddingReadTimeoutSec = 20;
+    ProjectSettings p;
+    p.embeddingConnectTimeoutSec = 600;
+    p.embeddingReadTimeoutSec = 600;
+    const CollectionMeta none;
+    const ResolvedEmbedding r = resolveEmbedding(g, &p, none);
+    EXPECT_EQ(r.connectTimeoutSec, 5u) << "a project must not be able to raise a shared limit";
+    EXPECT_EQ(r.readTimeoutSec, 20u);
+}
+
+TEST(EmbeddingTimeouts, LoweringTheGlobalTightensEveryProject) {
+    // Follows from min(), and is the reason a stored over-global value is kept
+    // rather than refused: it becomes meaningful again if the global drops.
+    Settings g;
+    g.embeddingConnectTimeoutSec = 10;
+    ProjectSettings p;
+    p.embeddingConnectTimeoutSec = 8;
+    const CollectionMeta none;
+    EXPECT_EQ(resolveEmbedding(g, &p, none).connectTimeoutSec, 8u);
+    g.embeddingConnectTimeoutSec = 3;
+    EXPECT_EQ(resolveEmbedding(g, &p, none).connectTimeoutSec, 3u);
+}
+
+TEST(EmbeddingTimeouts, AZeroOverrideIsUnsetRatherThanNoTimeout) {
+    // 0 means "no timeout" to the HTTP client, so reading a fat-fingered 0 as
+    // an override would produce precisely the unbounded call the budget split
+    // exists to prevent.
+    Settings g;
+    g.embeddingConnectTimeoutSec = 10;
+    g.embeddingReadTimeoutSec = 60;
+    ProjectSettings p;
+    p.embeddingConnectTimeoutSec = 0;
+    p.embeddingReadTimeoutSec = 0;
+    const CollectionMeta none;
+    const ResolvedEmbedding r = resolveEmbedding(g, &p, none);
+    EXPECT_EQ(r.connectTimeoutSec, 10u);
+    EXPECT_EQ(r.readTimeoutSec, 60u);
+}
+
+TEST(EmbeddingTimeouts, ATimeoutOnlyProjectCountsAsAnEmbeddingOverride) {
+    // Otherwise DELETE /settings/embeddings would report nothing to revert
+    // while a timeout override was still in force, and the settings document
+    // could be dropped with it.
+    ProjectSettings p;
+    p.embeddingReadTimeoutSec = 4;
+    EXPECT_TRUE(p.hasEmbeddingOverrides());
+    EXPECT_TRUE(p.hasAnyOverrides());
+}
+
+TEST(EmbeddingTimeouts, RoundTripThroughJson) {
+    ProjectSettings p;
+    EXPECT_FALSE(p.toJson().contains("embedding_connect_timeout_sec"));
+    p.embeddingConnectTimeoutSec = 2;
+    p.embeddingReadTimeoutSec = 4;
+    const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
+    ASSERT_TRUE(back.embeddingConnectTimeoutSec.has_value());
+    ASSERT_TRUE(back.embeddingReadTimeoutSec.has_value());
+    EXPECT_EQ(*back.embeddingConnectTimeoutSec, 2u);
+    EXPECT_EQ(*back.embeddingReadTimeoutSec, 4u);
+}
+
 // The per-project wall-time maximum. Resolved by a pure function for the same
 // reason the function policy is: the precedence is the behaviour, and it should
 // be assertable without a database, a runner or a clock.
 
 TEST(MaxFunctionWallTime, AbsentMeansNoProjectCap) {
     // 0, not "no time": the runner reads 0 as "the ceiling is the only cap".
-    EXPECT_EQ(maxFunctionWallTimeMsFor(nullptr), 0);
+    using K = functions::RunKind;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(nullptr, K::Http), 0);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(nullptr, K::Job), 0);
     const ProjectSettings p;
-    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 0);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Http), 0);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Job), 0);
 }
 
-TEST(MaxFunctionWallTime, UsesTheProjectValueWhenSet) {
+TEST(MaxFunctionWallTime, TheTwoKindsAreIndependent) {
+    // The whole point of splitting it: capping routes at 10 s must not cap
+    // cron work at 10 s. With one number the only safe setting was no cap.
+    using K = functions::RunKind;
     ProjectSettings p;
-    p.maxFunctionWallTimeMs = 30000;
-    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 30000);
+    p.maxFunctionWallTimeHttpMs = 10000;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Http), 10000);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Job), 0) << "an HTTP cap must not cap jobs";
+
+    p = ProjectSettings{};
+    p.maxFunctionWallTimeJobMs = 60000;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Job), 60000);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Http), 0) << "a job cap must not cap routes";
 }
 
 TEST(MaxFunctionWallTime, ANonPositiveStoredValueIsTreatedAsUnset) {
     // A fat-fingered 0 means "I did not mean to set one", not "no function in
     // this project may ever run".
+    using K = functions::RunKind;
     ProjectSettings p;
-    p.maxFunctionWallTimeMs = 0;
-    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 0);
-    p.maxFunctionWallTimeMs = -1;
-    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 0);
+    p.maxFunctionWallTimeHttpMs = 0;
+    p.maxFunctionWallTimeJobMs = -1;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Http), 0);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Job), 0);
 }
 
 TEST(MaxFunctionWallTime, RoundTripsAndIsNotWrittenWhenUnset) {
     ProjectSettings p;
+    EXPECT_FALSE(p.toJson().contains("max_function_wall_time_http_ms"));
+    EXPECT_FALSE(p.toJson().contains("max_function_wall_time_job_ms"));
     EXPECT_FALSE(p.toJson().contains("max_function_wall_time_ms"));
 
-    p.maxFunctionWallTimeMs = 45000;
+    p.maxFunctionWallTimeHttpMs = 5000;
+    p.maxFunctionWallTimeJobMs = 45000;
     const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
-    ASSERT_TRUE(back.maxFunctionWallTimeMs.has_value());
-    EXPECT_EQ(*back.maxFunctionWallTimeMs, 45000);
+    ASSERT_TRUE(back.maxFunctionWallTimeHttpMs.has_value());
+    ASSERT_TRUE(back.maxFunctionWallTimeJobMs.has_value());
+    EXPECT_EQ(*back.maxFunctionWallTimeHttpMs, 5000);
+    EXPECT_EQ(*back.maxFunctionWallTimeJobMs, 45000);
+}
+
+TEST(MaxFunctionWallTime, APreSplitDocumentSeedsBothKinds) {
+    // A document written before the split carries only the bare key and meant
+    // "both", so reading it must not silently drop the cap on either kind.
+    const ProjectSettings p =
+        ProjectSettings::fromJson({{"project", "p"}, {"max_function_wall_time_ms", 20000}});
+    using K = functions::RunKind;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Http), 20000);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Job), 20000);
+}
+
+TEST(MaxFunctionWallTime, APerKindKeyWinsOverTheBareOne) {
+    // Both spellings present is what a newer server writes, deliberately, so
+    // an older one still sees a cap. The per-kind value is the real one.
+    const ProjectSettings p = ProjectSettings::fromJson({{"project", "p"},
+                                                         {"max_function_wall_time_ms", 10000},
+                                                         {"max_function_wall_time_job_ms", 60000}});
+    using K = functions::RunKind;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Http), 10000);
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p, K::Job), 60000);
+}
+
+TEST(MaxFunctionWallTime, TheCompatKeyCarriesTheTighterOfTheTwo) {
+    // Written so a ROLLBACK to a server that only understands the bare key
+    // still enforces something. The tighter value, because a rollback that
+    // loosens a limit an admin set is the failure worth avoiding.
+    ProjectSettings p;
+    p.maxFunctionWallTimeHttpMs = 10000;
+    p.maxFunctionWallTimeJobMs = 60000;
+    const nlohmann::json j = p.toJson();
+    ASSERT_TRUE(j.contains("max_function_wall_time_ms"));
+    EXPECT_EQ(j.at("max_function_wall_time_ms").get<int64_t>(), 10000);
+
+    // One kind only: the compat key carries it rather than being omitted,
+    // otherwise a rollback would see no cap at all.
+    ProjectSettings jobOnly;
+    jobOnly.maxFunctionWallTimeJobMs = 30000;
+    EXPECT_EQ(jobOnly.toJson().at("max_function_wall_time_ms").get<int64_t>(), 30000);
 }
 
 TEST(MaxFunctionWallTime, ABudgetOnlyProjectIsNotTreatedAsEmpty) {
     // Otherwise clearing an embedding override would delete the settings
-    // document and silently remove the project's cap with it.
-    ProjectSettings p;
-    p.maxFunctionWallTimeMs = 1000;
-    EXPECT_TRUE(p.hasAnyOverrides());
-    EXPECT_FALSE(p.hasEmbeddingOverrides());
+    // document and silently remove the project's cap with it. Checked for each
+    // kind separately - a project that caps only jobs is still not empty.
+    ProjectSettings http;
+    http.maxFunctionWallTimeHttpMs = 1000;
+    EXPECT_TRUE(http.hasAnyOverrides());
+    EXPECT_FALSE(http.hasEmbeddingOverrides());
+
+    ProjectSettings job;
+    job.maxFunctionWallTimeJobMs = 1000;
+    EXPECT_TRUE(job.hasAnyOverrides());
+    EXPECT_FALSE(job.hasEmbeddingOverrides());
 }

Some files were not shown because too many files changed in this diff