Переглянути джерело

fix: the operational limits are configurable, not compiled in (0.18.1)

Swept for hardcoded operational values after the owner asked for it. The
sweep's own result is the finding: grepping for `constexpr k[A-Z]` found
fourteen constants and MISSED the most expensive number in the service,
because cpp-httplib sizes its request pool from hardware_concurrency and we
never set new_task_queue at all. A grep for our own literals cannot see a
default we inherited.

Now settable, DEFAULT UNCHANGED except where noted:
  http.thread_pool_size        boot    0 = httplib's own default
  database.timeout_ms          boot    5000, both binaries
  embedding_connect_cap_sec    hot     2  <- CHANGES behaviour, deliberately
  vector_filter_scan_cap       hot     10000
  captcha_connect_timeout_sec  hot     5
  captcha_read_timeout_sec     hot     10
  runtime.ctx_file_max_bytes   runner  0 = 1 MiB

The one behaviour change is the embedding split, and it is a defect fix.
resolveEmbedBudget capped connect at HALF the available time and nothing
else, so prod's connect 10 s / read 60 s turned a script's embedTimeoutMs
6000 into connect 3 s + read 3 s: a caller who budgeted six seconds for the
provider got a three-second read deadline, and the 504 then quoted 6000 ms,
a number no phase ever had. The phases are sequential, so the invariant is
connect + read <= available; an even split was never required. At the new
default that call gets connect 2 s + read 4 s. The half rule is KEPT as a
backstop, which is what stops a 2 s budget becoming connect 2 + read 1. Set
the cap to 0 for the old arithmetic exactly, and a test pins the defect so
what reverting costs stays visible. The 504 now names the deadline APPLIED
as well as the one asked for, and api/llms.txt's sentence about connect
taking half was REPLACED rather than labelled, because an API reference that
still describes the old split makes a consumer size their timeout wrongly.

Deliberately left hardcoded, because "make everything configurable" is a
different request: security bounds (secret name/value/count limits, the IMAP
literal ceiling, the file-name length) stay fixed, since an operator-settable
security limit widens what one misconfiguration can do; internal batching
stays fixed because it is an implementation decision, and mime_words' 45 is
RFC 2047's number. Named as still open rather than quietly skipped: the four
kRetryAfter* durations, kValuesLimitCap and kFallbackWallCeilingMs - the
Retry-After ones need settings reaching retryAfterSeconds(), which is pure by
design, and that injection deserves better than a hotfix.

A falsification caught that one change was untested: reverting vectorSearch
to the constant left test_vector_scan entirely green, because every test
there used the DEFAULT cap. Three tests now pass explicit caps. The residual
gap is written into the test file rather than implied - the opts.limit and
scan-exit uses inside vectorSearch need a live database and an oversized
collection, so a pass means the arithmetic obeys the cap and NOT that a
lowered setting is honoured end to end.

1361/1361 tests pass. The embed-cap change was falsified too: ignoring the
cap fails TheConnectCapGivesTheReadPhaseTheRestOfTheAsk alone.
fszontagh 3 тижнів тому
батько
коміт
3cc28e5893

+ 11 - 0
CLAUDE.md

@@ -668,6 +668,17 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   **A BACKUP OF A `conf.d` FILE MUST NOT LIVE IN `conf.d`.** The first instinct was `50-consistency.json.bak-20261023` beside the original; a loader that globs the directory would have read the backup as a second config file, and the boot log confirms the loader does merge drop-ins by name (`Merging drop-in: ...`). It went to `/var/backups/` instead. The dpkg-conffile rule says WHERE a drop-in goes; this is the matching rule for where its backup goes.
   **AND THE WINDOW'S REAL LESSON: THE SCRIPT DISCOVERED A MISSING TOOL WITH THE DATABASE ALREADY STOPPED. `rsync` IS NOT INSTALLED ON PROD.** The plan was a hot `cp -a` followed by a cold `rsync` delta, to keep downtime near the approved 90 s; `set -e` stopped the script at `rsync: command not found` after `systemctl stop smartbotic-database` had already returned. It failed safe - nothing was modified, the config was untouched and the service was simply down - and recovery was one `cp -a` of the full 5.1 GB, 29 s, so the window still came in at 88 s. **The generalisable form is the `pkill`-not-installed trap one layer up: verify every tool the window's script needs BEFORE the step that takes the service down**, because the cost of a missing binary is not the error, it is where in the sequence the error lands. A dry run of the script against a running box would have found it for nothing.
 
+- **EVERY OPERATIONAL LIMIT THAT HAD BITTEN US WAS A COMPILED-IN CONSTANT, AND THE ONE THAT MATTERED MOST WAS NOT A CONSTANT AT ALL - IT WAS A LIBRARY DEFAULT NOBODY HAD OVERRIDDEN (0.18.1).** Swept after the owner asked for it, and the sweep's own result is the lesson: grepping for `constexpr k[A-Z]` found fourteen constants and MISSED the most expensive number in the service, because cpp-httplib's request pool is sized by `max(8, hardware_concurrency - 1)` and we simply never set `new_task_queue`. A grep for OUR literals cannot see a default we inherited. **Ask what decides a behaviour, not where a number is written.**
+  Now configurable, with the DEFAULT UNCHANGED in every case but one:
+  - `http.thread_pool_size` (boot). **0 means cpp-httplib's own default**, never "no threads" - writing 8 would freeze today's httplib default into our config, so a future httplib sizing its pool better would be silently overridden by a stale copy. This is the lever on the measured cross-tenant degradation: prod is ONE vCPU, the default gives 8 request threads on one core, and one tenant's bulk write degraded every other tenant 5.6-9.5x uniformly. **Lowering it does not make the box faster, it moves WHERE the queueing happens** - fewer threads means a burst waits in the accept queue while the requests that do run keep their latency, instead of everything in flight slowing together. Which a deployment wants depends on whether its callers have timeouts, so there is no default we can pick for everyone. Logged at startup so the journal says which pool is in force.
+  - `database.timeout_ms` (boot, both binaries). Was a 5000 default argument on `DbGateway`. See the entry on the cold similarity search for why it fired.
+  - `embedding_connect_cap_sec` (settings, hot-reload). **The one default that CHANGES behaviour, to 2, because the old arithmetic was a defect.** `resolveEmbedBudget` capped connect at HALF the available time and nothing else, so prod's connect 10 s / read 60 s turned a script's `embedTimeoutMs: 6000` into connect 3 s + read 3 s - a caller who budgeted six seconds for the provider got a THREE second read deadline, and the 504 then quoted 6000 ms, **a number no phase ever had**. The phases are SEQUENTIAL, so the invariant is `connect + read <= available`; nothing ever required an even split. At the new default the same call gets connect 2 s + read 4 s. The half rule is KEPT as a backstop, which is what stops a 2 s budget becoming connect 2 + read 1 and overrunning the thing it was asked to fit inside. Set it to 0 to get the pre-0.18.1 arithmetic back exactly, and a test pins that defect so what reverting costs stays visible.
+  - `vector_filter_scan_cap` (settings). Only reachable against a database older than 2.14.0, where the walk can answer SHORT - 455 returned of 553 true matches on 12448 rows.
+  - `captcha_connect_timeout_sec` / `captcha_read_timeout_sec` (settings). Hardcoded 5 and 10, and the only outbound timeouts an operator could not move - on a path that runs INSIDE request handling, so a slow verifier holds a request thread where those are scarce.
+  - `runtime.ctx_file_max_bytes` (runner). It belongs beside `memory_limit_bytes` rather than in a header, because a run holds a pooled runtime of that size and base64 inflates by a third, so the two numbers have to be read together.
+  **WHAT WAS DELIBERATELY LEFT HARDCODED, because "make everything configurable" is not the same request.** SECURITY bounds stay fixed - `kMaxSecretNameLength`, `kMaxSecretValueBytes`, `kMaxSecretsPerProject`, `kMaxLiteral`, `kMaxNameLen` - since an operator-settable security limit widens what a single misconfiguration can do. INTERNAL batching stays fixed (`kMaxReclaimPerPass`, `kMaxTrimPerAppend`, `kNameLookupLimit`, `kDefaultListLimit`), because those are implementation decisions rather than operator questions, and `mime_words`'s 45 is RFC 2047's number and not ours to pick. Still OPEN and named rather than quietly skipped: the four `kRetryAfter*` durations in `errors.hpp`, `kValuesLimitCap`, and `kFallbackWallCeilingMs`. The Retry-After ones need settings reaching `retryAfterSeconds()`, which is deliberately PURE and has no settings access - a dependency injection worth doing properly rather than in a hotfix.
+  **AND A FALSIFICATION CAUGHT THAT ONE OF THESE CHANGES WAS UNTESTED, WHICH IS THE PART TO COPY.** Reverting `vectorSearch` to use the constant instead of its new `scanCap` parameter left the whole `test_vector_scan` file GREEN - 8 of 8 passing - because every test there calls the pure depth helpers with the DEFAULT cap and nothing exercised a custom one. Three tests now pass explicit caps, both lowered and raised. The remaining gap is stated in the test file rather than implied: `opts.limit = scanCap` and the `scan >= scanCap` exit inside `vectorSearch()` need a live database and a collection larger than the cap, so a pass there means "the walk's arithmetic obeys the cap" and NEVER "a lowered setting is honoured end to end".
+
 ## Deploy / publish
 
 **`VERSION` and `api/openapi.json`'s `info.version` must agree, and `packaging/build.sh` now refuses to build unless they do** (`scripts/check-version-sync.sh`, run at the top level so it covers the local, Docker and publish paths alike). They drifted once: 0.10.0 was published with the docs claiming 0.9.2, and since `openapi.json` ships in the server package and is served at `/openapi.json`, the stale value was live. **Correcting it cost a whole release**, because a published version number is never reused for different content - which is why 0.10.0 exists but must never be deployed. A release step that relies on remembering is a release step that gets skipped, so it is a check rather than a checklist line.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.18.0
+0.18.1

+ 1 - 1
api/llms.txt

@@ -320,7 +320,7 @@ export default async function (ctx) {
 - 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.
 - **An UNKNOWN option on a vector `/search` body is now refused with 422 `unknown_option`, naming every unrecognised key.** It used to be accepted and ignored, which produced silently wrong answers rather than errors. Measured on prod before the fix: `topK: 3` (the camelCase misspelling) returned **five** rows, the default, so a caller asking for three got five and was told nothing; `minScore: 0.99` returned rows where the correct `min_score: 0.99` returns none; and **`filter:` in the singular returned the rows the caller meant to EXCLUDE**. The accepted set is `query_text`, `query_vector`, `top_k`, `min_score`, `filters`, `embedTimeoutMs`. Matching is exact and case-sensitive, so `Top_K` is refused rather than quietly accepted as a second spelling.
 - **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. It applies identically to `.search()` and `.store()`: both resolve their vector through the same code, so there is no asymmetry between them. 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.
-- **Its RESOLUTION IS ONE SECOND, and the effective floor is 1 s per phase.** The HTTP client underneath takes whole seconds and treats 0 as "no timeout", so every value below 1000 ms resolves to the same thing: 1 s to connect plus 1 s to read. `embedTimeoutMs: 1` therefore allows up to **2 s**, not 1 ms, and a provider that answers inside that second succeeds normally - which reads exactly like the option being ignored. It is not: a value of 1 and a value of 999 are genuinely indistinguishable, and tuning inside that range does nothing. Ask for **2000 or more** if you want the split to be meaningful, and expect a timeout to surface at a whole-second boundary rather than at the millisecond you named. Connect never takes more than HALF the available time, so a 4000 ms ask becomes roughly 2 s connect + 2 s read.
+- **Its RESOLUTION IS ONE SECOND, and the effective floor is 1 s per phase.** The HTTP client underneath takes whole seconds and treats 0 as "no timeout", so every value below 1000 ms resolves to the same thing: 1 s to connect plus 1 s to read. `embedTimeoutMs: 1` therefore allows up to **2 s**, not 1 ms, and a provider that answers inside that second succeeds normally - which reads exactly like the option being ignored. It is not: a value of 1 and a value of 999 are genuinely indistinguishable, and tuning inside that range does nothing. Ask for **2000 or more** if you want the split to be meaningful, and expect a timeout to surface at a whole-second boundary rather than at the millisecond you named. **From 0.18.1 the split favours the READ phase, and this changed because the old split was a defect.** Connect is capped at an absolute 2 s (operator setting `embedding_connect_cap_sec`) and still never takes more than half the available time, so a 6000 ms ask now becomes **2 s connect + 4 s read** where it previously became 3 s + 3 s. That mattered: a consumer whose voice agent asks for exactly 6000 ms was getting a THREE second read deadline, and the 504 then quoted 6000 ms - a number no phase ever had. A 4000 ms ask is unchanged at 2 s + 2 s, since half of four is already two. The two phases are SEQUENTIAL, so what the option bounds is their sum; it was never a promise that connect gets half. **The 504 message now names the deadline that was applied as well as the one you asked for**, so `embedTimeoutMs 6000ms was applied as connect 2s + read 4s` tells you where the time went without reading our source.
 - **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, timeoutMs, responseType})` - 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.
 - **A job, cron or db run's `ctx` is NOT the HTTP shape.** It carries `trigger`, `depth`, `enqueued_by` and `enqueued_at_ms`, with your payload under **`ctx.body`** - there is no `ctx.method`, `ctx.path`, `ctx.query` or `ctx.params`. A cron payload is `{schedule, scheduled_at}`; a database-event payload is `{collection, table, id, event, document}`.

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.18.0",
+    "version": "0.18.1",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 12 - 0
runner/include/runner/host_context.hpp

@@ -110,6 +110,18 @@ struct HostContextConfig {
     /// stored. Either way the enqueued job gets depth + 1.
     uint32_t jobDepth = 0;
 
+    /// The most a single ctx.files.get() may pull into the JS heap, in bytes.
+    /// 0 means the compiled default (1 MiB).
+    ///
+    /// Separate from the HTTP upload cap because they answer different
+    /// questions: that one bounds what can be STORED, this one bounds what one
+    /// run may LOAD. It is configurable because the right value depends on the
+    /// runtime memory limit, which is itself configurable - a run holds a
+    /// pooled runtime (64 MiB on prod) and base64 inflates by a third, so an
+    /// operator raising this without raising that has made a footgun rather
+    /// than a feature, and the two numbers belong in the same file.
+    size_t ctxFileMaxBytes = 0;
+
     /// The deepest chain ctx.jobs.enqueue will extend. A function that enqueues
     /// itself - directly, or through two functions that enqueue each other -
     /// would otherwise run forever, and the cost is paid by every other tenant

+ 28 - 8
runner/src/host_context.cpp

@@ -158,7 +158,7 @@ JSValue throwApiError(JSContext* ctx, const ApiError& e) {
 /// A run holds a pooled runtime with its own memory limit (64 MiB on prod), and
 /// base64 inflates by a third, so a generous value here is a footgun rather
 /// than a feature.
-constexpr size_t kCtxFileMaxBytes = 1024 * 1024;
+constexpr size_t kCtxFileMaxBytesDefault = 1024 * 1024;
 
 namespace hostdetail {
 
@@ -603,7 +603,7 @@ EgressDecision decideEgress(const std::string& host, const functions::SsrfPolicy
 
 /// The most one ctx.mail call may pull off the wire, in bytes.
 ///
-/// The same question kCtxFileMaxBytes answers, asked about mail: not what a
+/// The same question kCtxFileMaxBytesDefault answers, asked about mail: not what a
 /// mailbox may hold, but what ONE run may load into a 64 MiB JS heap. A read of
 /// twenty messages' headers and text is tens of kilobytes, so this leaves room
 /// for a large message or two while still refusing the mailbox whose single
@@ -1679,6 +1679,7 @@ struct HostContext::Impl {
         want.configuredConnectSec = cfg.connectTimeoutSec;
         want.configuredReadSec = cfg.readTimeoutSec;
         want.callTimeoutMs = callTimeoutMs;
+        want.connectCapSec = global.embeddingConnectCapSec;
         const functions::EmbedBudget slice = functions::resolveEmbedBudget(want);
 
         EmbeddingClient emb(cfg.apiBase, cfg.apiKey, static_cast<uint32_t>(slice.connectSec),
@@ -1701,10 +1702,21 @@ struct HostContext::Impl {
             // 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.
+            // NAME THE DEADLINE THAT WAS ACTUALLY APPLIED, not the one asked
+            // for. This used to quote `callTimeoutMs` alone, so a script
+            // asking for 6000 ms was told it had exceeded 6000 ms when the
+            // phases it actually got were connect 3 s and read 3 s - a number
+            // no phase ever had, which sent an author looking for a provider
+            // taking over six seconds when the truth was that we had halved
+            // their budget. The asked-for value stays, because the author
+            // recognises it; what is added is what we did with it.
             if (slice.boundByCall)
                 throw ApiError(ErrCode::GatewayTimeout, "embedding_timeout",
-                               "the embedding call exceeded the embedTimeoutMs this call asked "
-                               "for (" + std::to_string(callTimeoutMs) + "ms)");
+                               "the embedding call exceeded the deadline it was given: "
+                               "embedTimeoutMs " + std::to_string(callTimeoutMs) +
+                               "ms was applied as connect " + std::to_string(slice.connectSec) +
+                               "s + read " + std::to_string(slice.readSec) +
+                               "s (the two phases are sequential, so their sum is the bound)");
             throw;
         }
     }
@@ -2019,7 +2031,13 @@ struct HostContext::Impl {
         const std::string c = qualify(config.project, collection);
         // The shared implementation, not a copy: a filter must mean the same
         // thing here as it does on the HTTP route, scan cap included.
-        const VectorSearchResult found = vectorSearch(db.client(), c, q, topK, minScore, filters);
+        // Same settings-driven cap as the HTTP route, from the same global
+        // snapshot: a filter must mean the same thing on both surfaces, and
+        // that now includes how deep the walk goes.
+        loadSettings();
+        const uint32_t scanCap = global.vectorFilterScanCap;
+        const VectorSearchResult found =
+            vectorSearch(db.client(), c, q, topK, minScore, filters, scanCap);
 
         // The console warning STAYS - it is what an author reading a run log
         // sees. But it is no longer the only signal, because a console line
@@ -2031,7 +2049,7 @@ struct HostContext::Impl {
         // confidence. The structured signal is added below, next to the hits.
         if (found.scanCapped)
             addLog("[warn] search on '" + collection + "' stopped at the " +
-                   std::to_string(kVectorFilterScanCap) +
+                   std::to_string(scanCap == 0 ? kVectorFilterScanCap : scanCap) +
                    "-candidate scan cap while still short of top_k " +
                    std::to_string(topK) + ": more rows may match than were returned");
 
@@ -2425,11 +2443,13 @@ struct HostContext::Impl {
         // not be able to pull megabytes into a 64 MiB JS heap on every run
         // afterwards. Refused rather than truncated - half a PNG is worse than
         // an error.
-        if (got->second.size() > kCtxFileMaxBytes)
+        const size_t fileCap = config.ctxFileMaxBytes > 0 ? config.ctxFileMaxBytes
+                                                          : kCtxFileMaxBytesDefault;
+        if (got->second.size() > fileCap)
             throw ApiError(ErrCode::Unprocessable, "file_too_large",
                            "'" + name + "' is " + std::to_string(got->second.size()) +
                                " bytes, which is more than a function may load (" +
-                               std::to_string(kCtxFileMaxBytes) + ")");
+                               std::to_string(fileCap) + ")");
 
         nlohmann::json out = got->first.toJson();
         out["base64"] = hostdetail::base64Encode(

+ 15 - 3
runner/src/main.cpp

@@ -108,6 +108,11 @@ struct RunnerConfig {
 
     size_t poolSize = 4;
     size_t memoryLimitBytes = 128u * 1024 * 1024;
+    /// The most a single ctx.files.get() may pull into the JS heap. 0 means the
+    /// compiled default (1 MiB). It lives beside memoryLimitBytes on purpose:
+    /// a run holds a pooled runtime of that size and base64 inflates by a
+    /// third, so the two numbers have to be read together.
+    size_t ctxFileMaxBytes = 0;
     /// Ceiling for a run an HTTP request triggered. Kept at two seconds: a
     /// client is waiting on it, and vectorapi's read timeout is sized against
     /// this number.
@@ -185,6 +190,7 @@ struct RunnerConfig {
             const auto& r = j["runtime"];
             c.poolSize = r.value("pool_size", c.poolSize);
             c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes);
+            c.ctxFileMaxBytes = r.value("ctx_file_max_bytes", c.ctxFileMaxBytes);
             // `max_wall_time_ms` keeps its old name and its old meaning - the
             // HTTP ceiling - so an existing conffile is not silently
             // reinterpreted. `max_http_wall_time_ms` is the clearer spelling
@@ -450,12 +456,15 @@ private:
 class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
 public:
     GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment,
-                        std::shared_ptr<svapi::runner::JobPort> jobs)
-        : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)) {}
+                        std::shared_ptr<svapi::runner::JobPort> jobs,
+                        size_t ctxFileMaxBytes = 0)
+        : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)),
+          ctxFileMaxBytes_(ctxFileMaxBytes) {}
 
     bool create(const Request& request, svapi::runner::HostBindingsLease& out,
                 std::string& error) override {
         svapi::runner::HostContextConfig cfg;
+        cfg.ctxFileMaxBytes = ctxFileMaxBytes_;
         cfg.project = request.project;
         cfg.functionId = request.functionId;
         cfg.policy = request.policy;
@@ -499,6 +508,8 @@ private:
     /// Null when the queue is not available, which ctx.jobs reports as
     /// `jobs_unavailable` rather than pretending to enqueue.
     std::shared_ptr<svapi::runner::JobPort> jobs_;
+    /// 0 means HostContext's own default; see runtime.ctx_file_max_bytes.
+    size_t ctxFileMaxBytes_ = 0;
 };
 
 /// Parse a request body, or answer 400 with the same error envelope the rest of
@@ -605,7 +616,8 @@ int main(int argc, char** argv) {
 
     // Snapshot the environment once: it does not change under a running
     // process, and re-reading it per run would be work for no gain.
-    GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort);
+    GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort,
+                             cfg.ctxFileMaxBytes);
     svapi::runner::RunService service(source, options, &host);
 
     // THE thing that drains the queue. Without it the scheduler enqueues a job,

+ 2 - 1
src/captcha.cpp

@@ -15,7 +15,8 @@ bool verifyCaptcha(const Settings& s, const std::string& token, const std::strin
     std::string path   = (slash == std::string::npos) ? "/"  : url.substr(slash);
     httplib::Client cli(origin);
     applyOutboundDefaults(cli);
-    cli.set_connection_timeout(5); cli.set_read_timeout(10);
+    cli.set_connection_timeout(s.captchaConnectTimeoutSec);
+    cli.set_read_timeout(s.captchaReadTimeoutSec);
     httplib::Params params{{"secret", s.captchaSecret}, {"response", token}, {"remoteip", remoteIp}};
     auto res = cli.Post(path, params);
     if (!res || res->status != 200) return false;

+ 1 - 0
src/config.cpp

@@ -11,6 +11,7 @@ Config Config::fromJson(const nlohmann::json& j) {
         const auto& h = j["http"];
         c.httpBind = h.value("bind_address", c.httpBind);
         c.httpPort = h.value("port", c.httpPort);
+        c.httpThreadPoolSize = h.value("thread_pool_size", c.httpThreadPoolSize);
     }
     if (j.contains("database") && j["database"].is_object()) {
         c.dbAddress = j["database"].value("address", c.dbAddress);

+ 28 - 0
src/config.hpp

@@ -10,6 +10,34 @@ struct Config {
     std::string logLevel  = "info";
     std::string httpBind  = "0.0.0.0";
     uint16_t    httpPort  = 8080;
+    /// Request threads. 0 means "cpp-httplib's own default", which is
+    /// `max(8, hardware_concurrency - 1)`.
+    ///
+    /// It exists because that default is wrong in BOTH directions on a small
+    /// box and there was no way to move it. Measured on prod 2026-10-20, which
+    /// is ONE vCPU: one tenant's bulk write degraded every other tenant by
+    /// 5.6-9.5x, UNIFORMLY, including projects whose collections it never
+    /// touched. `nproc` is 1 there, so the default gives 8 request threads on
+    /// one core - concurrency without parallelism, where 8 busy threads each
+    /// take about 8x longer. The measured range lands on that number, which is
+    /// why it is corroboration rather than coincidence.
+    ///
+    /// Lowering it does not make the box faster; it changes WHERE the queueing
+    /// happens. With fewer threads a burst waits in the accept queue and the
+    /// requests that do run keep their latency, instead of every request in
+    /// flight slowing down together. Which of those a deployment wants depends
+    /// on whether its callers have timeouts, so it is an operator's decision
+    /// and not a default we can pick for everyone.
+    ///
+    /// Raising it is the other direction and has its own trap: a lease is held
+    /// for a whole request, so more threads on one core means more concurrent
+    /// slow requests rather than more throughput.
+    ///
+    /// 0 rather than 8 as the default, deliberately: writing a number here
+    /// would freeze today's httplib default into our config, and then a
+    /// future httplib that sized its pool better would be silently overridden
+    /// by a stale copy of the old behaviour.
+    uint32_t    httpThreadPoolSize = 0;
     std::string dbAddress = "localhost:9004";
     /// Per-call gRPC deadline for EVERY database call, in milliseconds.
     ///

+ 35 - 5
src/functions/embed_budget.hpp

@@ -35,6 +35,23 @@ struct EmbedBudgetRequest {
     /// 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;
+    /// ABSOLUTE ceiling on the connect phase, in seconds. 0 means "not set",
+    /// which falls back to the half-of-budget rule alone.
+    ///
+    /// THIS EXISTS BECAUSE THE HALF RULE ALONE WAS A DEFECT, NOT A SAFETY NET.
+    /// With prod's configured connect 10 s and read 60 s, a script asking for
+    /// `embedTimeoutMs: 6000` got connect 3 s and read 3 s - so a caller who
+    /// had budgeted six seconds for the provider was given a THREE second read
+    /// deadline, and the error then quoted 6000 ms, a number no phase ever
+    /// had. Measured against a consumer's live voice agent, whose first
+    /// attempt is exactly 6000 ms.
+    ///
+    /// The two phases are SEQUENTIAL, so what has to hold is
+    /// `connect + read <= available`; nothing requires connect to be given
+    /// half. A reachable provider completes a TLS connect in well under a
+    /// second, so a small absolute cap leaves the rest to the read phase,
+    /// which is where a slow-but-working provider actually spends its time.
+    int64_t connectCapSec = 0;
 };
 
 struct EmbedBudget {
@@ -57,10 +74,15 @@ struct EmbedBudget {
 /// 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.
+/// Connect gets at most `connectCapSec`, and never more than 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.
+///
+/// The half rule used to be the ONLY bound and that was the defect: a 6 s call
+/// budget became connect 3 s + read 3 s, so a caller's six-second allowance
+/// bought a three-second read. The phases are sequential, so the invariant to
+/// keep is `connect + read <= available`, not an even split.
 inline EmbedBudget resolveEmbedBudget(const EmbedBudgetRequest& in) {
     EmbedBudget out;
 
@@ -75,7 +97,15 @@ inline EmbedBudget resolveEmbedBudget(const EmbedBudgetRequest& in) {
     int64_t availableSec = (availableMs + 999) / 1000;
     if (availableSec < 1) availableSec = 1;
 
-    const int64_t connectCap = std::max<int64_t>(1, availableSec / 2);
+    // Connect is bounded by THREE things and takes the smallest: the
+    // operator's configured connect timeout, the absolute cap, and half the
+    // available time. The half rule is kept as a FLOOR-PRESERVING backstop
+    // rather than as the primary bound - without it a 2 s budget with a 2 s
+    // cap would give connect 2 and read 1, breaking `connect + read <=
+    // available`. With it, a small budget still splits and a large one no
+    // longer hands most of the time to a phase that cannot use it.
+    int64_t connectCap = std::max<int64_t>(1, availableSec / 2);
+    if (in.connectCapSec > 0) connectCap = std::min(connectCap, in.connectCapSec);
     out.connectSec = in.configuredConnectSec > 0
                          ? std::min(in.configuredConnectSec, connectCap)
                          : connectCap;

+ 9 - 2
src/handlers/vectors.cpp

@@ -127,8 +127,14 @@ void registerVectorRoutes(ApiServer& s) {
         auto filters = parseSearchFilters(body);
         const std::string coll = qualify(project, name);
 
+        // The cap comes from the settings snapshot rather than the compiled
+        // constant, so an operator can raise it for a collection larger than
+        // it. Read once and reused below, because `scan_cap` must report the
+        // value the walk ACTUALLY used - reporting the constant while the walk
+        // obeyed a setting is the flag-instead-of-the-bytes failure.
+        const uint32_t scanCap = d->settings.snapshot()->vectorFilterScanCap;
         const VectorSearchResult found =
-            vectorSearch(d->db.client(), coll, q, topK, minScore, filters);
+            vectorSearch(d->db.client(), coll, q, topK, minScore, filters, scanCap);
 
         nlohmann::json arr = nlohmann::json::array();
         for (const auto& r : found.hits)
@@ -162,7 +168,8 @@ void registerVectorRoutes(ApiServer& s) {
         // Conditional on purpose, and the condition is the one a caller needs:
         // whenever `scan_capped` is true this is present, so "if capped, read
         // the cap" is safe and nobody has to hardcode the number.
-        if (found.scanCapped) out["scan_cap"] = kVectorFilterScanCap;
+        if (found.scanCapped)
+            out["scan_cap"] = scanCap == 0 ? kVectorFilterScanCap : scanCap;
         sendJson(res, 200, out);
     });
 }

+ 10 - 0
src/main.cpp

@@ -174,6 +174,16 @@ int main(int argc, char** argv) {
     }
 
     server.registerRoutes();
+    // Before listen, or cpp-httplib has already built its queue and this is
+    // silently ignored. Logged either way so the journal says which pool is in
+    // force; "default" rather than a number, because the number belongs to
+    // httplib and guessing it here is how a doc goes stale.
+    server.setThreadPoolSize(cfg.httpThreadPoolSize);
+    if (cfg.httpThreadPoolSize > 0)
+        spdlog::info("http request threads: {}", cfg.httpThreadPoolSize);
+    else
+        spdlog::info("http request threads: cpp-httplib default (max(8, nproc-1)); "
+                     "set http.thread_pool_size to override");
 
     std::thread http([&] {
         spdlog::info("listening on {}:{}", cfg.httpBind, cfg.httpPort);

+ 5 - 0
src/server.cpp

@@ -264,6 +264,11 @@ void ApiServer::registerRoutes() {
     if (!d_.webuiDir.empty()) svr_.set_mount_point("/", d_.webuiDir);
 }
 
+void ApiServer::setThreadPoolSize(uint32_t n) {
+    if (n == 0) return;  // leave cpp-httplib's own default alone
+    svr_.new_task_queue = [n] { return new httplib::ThreadPool(n); };
+}
+
 int  ApiServer::bindToAnyPort(const std::string& host) { return svr_.bind_to_any_port(host); }
 void ApiServer::listenAfterBind() { svr_.listen_after_bind(); }
 bool ApiServer::listen(const std::string& host, uint16_t port) { return svr_.listen(host, port); }

+ 9 - 0
src/server.hpp

@@ -43,6 +43,15 @@ class ApiServer {
 public:
     explicit ApiServer(ServerDeps deps);
     void registerRoutes();
+    /// Size the request thread pool. 0 leaves cpp-httplib's own default
+    /// (`max(8, hardware_concurrency - 1)`) in place.
+    ///
+    /// MUST be called before listen(): cpp-httplib builds the queue when the
+    /// server starts accepting, so setting it afterwards is silently ignored -
+    /// the accepted-and-discarded shape this codebase keeps meeting. main()
+    /// calls it before listen and logs the effective value, so an operator can
+    /// see from the journal which number is in force rather than inferring it.
+    void setThreadPoolSize(uint32_t n);
     int  bindToAnyPort(const std::string& host);
     void listenAfterBind();
     bool listen(const std::string& host, uint16_t port);

+ 8 - 0
src/settings.cpp

@@ -14,6 +14,10 @@ Settings Settings::fromJson(const nlohmann::json& j) {
     s.defaultProject             = j.value("default_project", s.defaultProject);
     s.embeddingConnectTimeoutSec = j.value("embedding_connect_timeout_sec", s.embeddingConnectTimeoutSec);
     s.embeddingReadTimeoutSec    = j.value("embedding_read_timeout_sec", s.embeddingReadTimeoutSec);
+    s.embeddingConnectCapSec     = j.value("embedding_connect_cap_sec",   s.embeddingConnectCapSec);
+    s.vectorFilterScanCap        = j.value("vector_filter_scan_cap",      s.vectorFilterScanCap);
+    s.captchaConnectTimeoutSec   = j.value("captcha_connect_timeout_sec",  s.captchaConnectTimeoutSec);
+    s.captchaReadTimeoutSec      = j.value("captcha_read_timeout_sec",     s.captchaReadTimeoutSec);
     s.embeddingCacheSize         = j.value("embedding_cache_size",        s.embeddingCacheSize);
     s.embeddingCacheTtlSec       = j.value("embedding_cache_ttl_sec",     s.embeddingCacheTtlSec);
     s.embeddingCacheMaxBytes     = j.value("embedding_cache_max_bytes",   s.embeddingCacheMaxBytes);
@@ -43,6 +47,10 @@ nlohmann::json Settings::toJson() const {
             {"default_project", defaultProject},
             {"embedding_connect_timeout_sec", embeddingConnectTimeoutSec},
             {"embedding_read_timeout_sec", embeddingReadTimeoutSec},
+            {"embedding_connect_cap_sec",  embeddingConnectCapSec},
+            {"vector_filter_scan_cap",     vectorFilterScanCap},
+            {"captcha_connect_timeout_sec", captchaConnectTimeoutSec},
+            {"captcha_read_timeout_sec",   captchaReadTimeoutSec},
             {"embedding_cache_size",        embeddingCacheSize},
             {"embedding_cache_ttl_sec",     embeddingCacheTtlSec},
             {"embedding_cache_max_bytes",   embeddingCacheMaxBytes},

+ 32 - 0
src/settings.hpp

@@ -16,6 +16,38 @@ struct Settings {
     std::string defaultProject           = "default";
     uint32_t    embeddingConnectTimeoutSec = 10;
     uint32_t    embeddingReadTimeoutSec    = 60;
+    /// ABSOLUTE ceiling on the connect phase of an embedding call, in seconds.
+    /// 0 disables it and restores the old half-of-budget rule alone.
+    ///
+    /// Default 2, which is a CHANGE in effective behaviour and is the point:
+    /// the half rule gave a 6 s call budget connect 3 s + read 3 s, so a
+    /// caller's six seconds bought a three-second read. At 2 the same call
+    /// gets connect 2 s + read 4 s. A reachable provider completes a TLS
+    /// connect in well under a second, so 2 keeps an order of magnitude of
+    /// margin while leaving the rest where a slow provider actually spends it.
+    ///
+    /// Set it to the configured connect timeout to opt out, or to 0 to get the
+    /// pre-0.18.1 arithmetic back exactly.
+    uint32_t    embeddingConnectCapSec     = 2;
+    /// How deep the EMULATED filtered vector walk may go into the ranking.
+    /// 0 means the compiled default (10000).
+    ///
+    /// Only reachable against a database older than 2.14.0: from 2.14.0 the
+    /// filters select candidates before ranking, so that path is exact and
+    /// uncapped and ignores this. It matters because a collection with more
+    /// rows than the cap can answer a filtered search SHORT - measured at 455
+    /// returned of 553 true matches on 12448 rows - and whether that is
+    /// acceptable depends on the deployment's data rather than on a number
+    /// compiled in here. Raising it costs round trips, which is why it is not
+    /// simply set high.
+    uint32_t    vectorFilterScanCap         = 10000;
+    /// Timeouts for the captcha verification call, in seconds. They were
+    /// hardcoded 5 and 10 in captcha.cpp, which made them the only outbound
+    /// timeouts in the service an operator could not move - and this call sits
+    /// INSIDE request handling, so a slow verifier holds a request thread on a
+    /// box where those are scarce.
+    uint32_t    captchaConnectTimeoutSec   = 5;
+    uint32_t    captchaReadTimeoutSec      = 10;
     uint32_t    embeddingCacheSize         = 4096;       // max entries
     uint32_t    embeddingCacheTtlSec       = 86400;      // 0 = no expiry
     uint64_t    embeddingCacheMaxBytes     = 268435456;  // 256 MB

+ 7 - 5
src/vector_search.cpp

@@ -30,8 +30,10 @@ void markServerFilteringUnsupported() {
 VectorSearchResult vectorSearch(
     smartbotic::database::Client& client, const std::string& coll,
     const std::vector<float>& query, uint32_t topK, float minScore,
-    const std::vector<smartbotic::database::Client::Filter>& filters) {
+    const std::vector<smartbotic::database::Client::Filter>& filters,
+    uint32_t scanCap) {
     VectorSearchResult out;
+    if (scanCap == 0) scanCap = kVectorFilterScanCap;
     if (filters.empty()) {
         out.hits = client.similaritySearch(coll, query, topK, minScore);
         out.mode = VectorSearchResult::Mode::NoFilter;
@@ -90,7 +92,7 @@ VectorSearchResult vectorSearch(
 
     smartbotic::database::Client::QueryOptions opts;
     opts.filters = filters;
-    opts.limit   = kVectorFilterScanCap;
+    opts.limit   = scanCap;
     std::unordered_set<std::string> allowed;
     // Bind the result before iterating: a range-for over a temporary dangles.
     const std::vector<nlohmann::json> matched = client.find(coll, opts);
@@ -105,7 +107,7 @@ VectorSearchResult vectorSearch(
     // the ranking is exhausted. Because the scan is in descending score order,
     // stopping as soon as topK matches are collected still yields the true
     // topK: anything unseen scores lower than everything already kept.
-    uint32_t scan = firstScanDepth(topK, allowed.size());
+    uint32_t scan = firstScanDepth(topK, allowed.size(), scanCap);
     while (true) {
         const std::vector<smartbotic::database::Client::SimilarityResult> page =
             client.similaritySearch(coll, query, scan, minScore);
@@ -118,7 +120,7 @@ VectorSearchResult vectorSearch(
         out.scanned = scan;
         if (results.size() >= topK) break;            // enough matches
         if (page.size() < scan) break;                // ranking exhausted: complete
-        if (scan >= kVectorFilterScanCap) {
+        if (scan >= scanCap) {
             // Short of topK, and the ranking still had more to give. This is
             // the ONLY branch that produces an incomplete answer, so it is the
             // only one that sets the flag - a filter that merely matches fewer
@@ -128,7 +130,7 @@ VectorSearchResult vectorSearch(
             break;
         }
         // The decision itself is pure and tested in vector_search.hpp.
-        scan = nextScanDepth(scan, topK, results.size());
+        scan = nextScanDepth(scan, topK, results.size(), scanCap);
     }
     out.hits = std::move(results);
     out.mode = VectorSearchResult::Mode::Walk;

+ 12 - 1
src/vector_search.hpp

@@ -142,9 +142,20 @@ constexpr const char* filterModeName(VectorSearchResult::Mode m) {
     return "none";
 }
 
+/// @param scanCap  how deep into the ranking the emulated walk may go. 0 means
+///                 `kVectorFilterScanCap`. It is a PARAMETER rather than the
+///                 constant because it decides whether a filtered sweep can be
+///                 complete on a large collection, and that depends on the
+///                 deployment's data rather than on a number compiled in here:
+///                 a collection with more rows than the cap can return a
+///                 silently short answer, which is why `scanCapped` exists.
+///                 The constant remains the default so no caller changes
+///                 meaning, and the server-side filtered path (2.14.0+) is
+///                 uncapped and ignores it entirely.
 VectorSearchResult vectorSearch(
     smartbotic::database::Client& client, const std::string& qualifiedCollection,
     const std::vector<float>& query, uint32_t topK, float minScore,
-    const std::vector<smartbotic::database::Client::Filter>& filters);
+    const std::vector<smartbotic::database::Client::Filter>& filters,
+    uint32_t scanCap = kVectorFilterScanCap);
 
 } // namespace svapi

+ 7 - 1
tests/test_config.cpp

@@ -15,12 +15,17 @@ TEST(Config, DefaultsWhenEmpty) {
     // slow database call reaches a caller as a 503 or as a late 200, which is
     // a decision for whoever sets it rather than for a release.
     EXPECT_EQ(c.dbTimeoutMs, 5000u);
+    // 0 means "cpp-httplib's own default", NOT "no threads". Writing 8 here
+    // would freeze today's httplib default into our config, so a future
+    // httplib that sized its pool better would be silently overridden by a
+    // stale copy of the old behaviour.
+    EXPECT_EQ(c.httpThreadPoolSize, 0u);
 }
 
 TEST(Config, ParsesProvidedValues) {
     auto j = nlohmann::json::parse(R"({
         "log_level":"debug",
-        "http":{"bind_address":"127.0.0.1","port":9090},
+        "http":{"bind_address":"127.0.0.1","port":9090,"thread_pool_size":2},
         "database":{"address":"db:9004","timeout_ms":20000}
     })");
     Config c = Config::fromJson(j);
@@ -29,6 +34,7 @@ TEST(Config, ParsesProvidedValues) {
     EXPECT_EQ(c.httpPort, 9090);
     EXPECT_EQ(c.dbAddress, "db:9004");
     EXPECT_EQ(c.dbTimeoutMs, 20000u);
+    EXPECT_EQ(c.httpThreadPoolSize, 2u);
 }
 
 // The pairing that makes the test above mean something: a `database` block

+ 82 - 0
tests/test_embed_budget.cpp

@@ -181,3 +181,85 @@ TEST(EmbedBudget, AboveTheFloorTheAskIsActuallyHonoured) {
 }
 
 } // namespace
+
+// ---------------------------------------------------------------------------
+// The absolute connect cap (0.18.1). The half rule alone was a defect, and
+// these pin the defect, the fix, and that the fix cannot break the invariant.
+// ---------------------------------------------------------------------------
+
+TEST(EmbedBudget, THE_DEFECT_aSixSecondAskBoughtAThreeSecondRead) {
+    // Prod's exact configuration and a consumer's exact first attempt, which
+    // is how this was found: their voice agent asks for 6000 ms, prod has
+    // connect 10 s and read 60 s, and the half rule handed the read phase
+    // three seconds. Kept as a test rather than deleted, because this is the
+    // behaviour an operator gets back by setting the cap to 0, and it has to
+    // stay visible that doing so costs them this.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 15000;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    in.callTimeoutMs = 6000;
+    in.connectCapSec = 0;            // the pre-0.18.1 arithmetic
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 3);
+    EXPECT_EQ(b.readSec, 3) << "half of a 6 s ask, which is the defect";
+}
+
+TEST(EmbedBudget, TheConnectCapGivesTheReadPhaseTheRestOfTheAsk) {
+    // Same call, with the shipped default cap of 2. Connect keeps an order of
+    // magnitude more than a TLS handshake needs and the read phase gets the
+    // rest, which is what the caller was budgeting for.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 15000;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    in.callTimeoutMs = 6000;
+    in.connectCapSec = 2;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 2);
+    EXPECT_EQ(b.readSec, 4);
+    EXPECT_LE(b.connectSec + b.readSec, 6) << "the phases are sequential";
+    EXPECT_TRUE(b.boundByCall);
+}
+
+TEST(EmbedBudget, TheCapNeverBreaksTheSumInvariantOnASmallBudget) {
+    // The half rule is KEPT as a backstop precisely for this: a 2 s budget
+    // with a 2 s cap must not yield connect 2 + read 1, which would overrun
+    // the budget it was asked to fit inside.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 2000;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    in.connectCapSec = 2;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 1);
+    EXPECT_EQ(b.readSec, 1);
+    EXPECT_LE(b.connectSec + b.readSec, 2);
+}
+
+TEST(EmbedBudget, TheCapNarrowsAndNeverWidens) {
+    // A cap ABOVE what the half rule allows must change nothing, or the knob
+    // could be used to widen connect past the budget split - the same
+    // narrowing-only discipline the per-project timeouts already follow.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 6000;
+    in.configuredConnectSec = 10;
+    in.configuredReadSec = 60;
+    in.connectCapSec = 30;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 3) << "the half rule still binds";
+    EXPECT_LE(b.connectSec + b.readSec, 6);
+}
+
+TEST(EmbedBudget, AConfiguredConnectBelowTheCapStillWins) {
+    // The cap is a ceiling, not a floor: an operator who deliberately set a
+    // 1 s connect timeout must keep it rather than be raised to the cap.
+    EmbedBudgetRequest in;
+    in.remainingBudgetMs = 60000;
+    in.configuredConnectSec = 1;
+    in.configuredReadSec = 60;
+    in.connectCapSec = 2;
+    const auto b = resolveEmbedBudget(in);
+    EXPECT_EQ(b.connectSec, 1);
+    EXPECT_EQ(b.readSec, 59);
+}

+ 53 - 0
tests/test_settings.cpp

@@ -90,3 +90,56 @@ TEST(ApiKey, GenerateIsHexAndUnique) {
     EXPECT_NE(a, b);
     for (char c : a) EXPECT_TRUE(std::isxdigit(static_cast<unsigned char>(c)));
 }
+
+// ---------------------------------------------------------------------------
+// 0.18.1: values that used to be compiled in. Each default is pinned, because
+// the point of making them settings is that an operator can move them - and a
+// default that drifts silently changes behaviour for every deployment that
+// never set it.
+// ---------------------------------------------------------------------------
+
+TEST(Settings, OperationalLimitDefaults) {
+    Settings s = Settings::fromJson(nlohmann::json::object());
+    // 2, not 0 and not the configured connect timeout. This is the one default
+    // in this group that CHANGES behaviour relative to 0.18.0, deliberately:
+    // the half-of-budget rule alone gave a 6 s embedding ask connect 3 s and
+    // read 3 s, so a caller's six seconds bought a three-second read.
+    EXPECT_EQ(s.embeddingConnectCapSec, 2u);
+    // Unchanged from the constants they replace, so no deployment that never
+    // sets them behaves differently.
+    EXPECT_EQ(s.vectorFilterScanCap, 10000u);
+    EXPECT_EQ(s.captchaConnectTimeoutSec, 5u);
+    EXPECT_EQ(s.captchaReadTimeoutSec, 10u);
+}
+
+TEST(Settings, OperationalLimitsRoundTrip) {
+    auto j = nlohmann::json::parse(R"({
+        "embedding_connect_cap_sec": 1,
+        "vector_filter_scan_cap": 50000,
+        "captcha_connect_timeout_sec": 3,
+        "captcha_read_timeout_sec": 7
+    })");
+    Settings s = Settings::fromJson(j);
+    EXPECT_EQ(s.embeddingConnectCapSec, 1u);
+    EXPECT_EQ(s.vectorFilterScanCap, 50000u);
+    EXPECT_EQ(s.captchaConnectTimeoutSec, 3u);
+    EXPECT_EQ(s.captchaReadTimeoutSec, 7u);
+    // Through the document and back, because these are stored in the settings
+    // collection and a field that parses but is not emitted is lost on the
+    // next write - which would look like the operator's change being reverted.
+    EXPECT_EQ(Settings::fromJson(s.toJson()).toJson(), s.toJson());
+    Settings again = Settings::fromJson(s.toJson());
+    EXPECT_EQ(again.embeddingConnectCapSec, 1u);
+    EXPECT_EQ(again.vectorFilterScanCap, 50000u);
+}
+
+TEST(Settings, AZeroConnectCapIsUnsetRatherThanNoConnectTime) {
+    // 0 means "no absolute cap, fall back to the half rule" - it must never
+    // reach the HTTP client as a zero connect timeout, which to cpp-httplib
+    // means NO timeout and is the unbounded call the whole split prevents.
+    // resolveEmbedBudget enforces that; this pins that 0 survives the config
+    // round trip as 0 rather than being coerced to the default.
+    Settings s = Settings::fromJson(nlohmann::json::parse(R"({"embedding_connect_cap_sec":0})"));
+    EXPECT_EQ(s.embeddingConnectCapSec, 0u);
+    EXPECT_EQ(Settings::fromJson(s.toJson()).embeddingConnectCapSec, 0u);
+}

+ 43 - 0
tests/test_vector_scan.cpp

@@ -86,3 +86,46 @@ TEST(VectorScan, ALargeScanTimesTopKDoesNotOVERFLOW) {
     EXPECT_LE(nextScanDepth(kVectorFilterScanCap, 4000000000u, 1), kVectorFilterScanCap);
     EXPECT_GT(nextScanDepth(1000, 4000000000u, 1), 1000u);
 }
+
+// ---------------------------------------------------------------------------
+// 0.18.1: the cap is a PARAMETER now (settings `vector_filter_scan_cap`), not
+// only the compiled constant. Every test above uses the default, so before
+// these there was nothing asserting a custom cap is honoured anywhere - and a
+// deliberate falsification confirmed it: reverting vectorSearch to use the
+// constant left the whole file green.
+//
+// COVERAGE STATED RATHER THAN IMPLIED. These cover the two pure decisions,
+// which is where the cap is consumed on every pass. What they do NOT cover is
+// `opts.limit = scanCap` and the `scan >= scanCap` exit inside vectorSearch(),
+// because that needs a live database and a collection larger than the cap.
+// Read a pass here as "the walk's arithmetic obeys the cap", never as "a
+// lowered setting is honoured end to end".
+// ---------------------------------------------------------------------------
+
+TEST(VectorScan, ALoweredCapBoundsTheFirstPass) {
+    // The whole point of making it settable is that a smaller value really
+    // bounds the walk. With a cap of 100, a filter matching fewer rows than
+    // topK goes to 100 rather than to the compiled 10000.
+    EXPECT_EQ(firstScanDepth(500, 300, 100), 100u);
+    EXPECT_LE(firstScanDepth(5000, 100000, 100), 100u);
+    // And the 64 floor still applies below it, so a tiny cap cannot produce a
+    // first pass of 4 - which would turn one round trip into many.
+    EXPECT_EQ(firstScanDepth(1, 100000, 100), 64u);
+}
+
+TEST(VectorScan, ALoweredCapBoundsEveryWideningStep) {
+    EXPECT_EQ(nextScanDepth(2000, 500, 89, 4000), 4000u);
+    EXPECT_LE(nextScanDepth(50, 500, 1, 200), 200u);
+    // The x4 floor is still a floor, but clamped by the cap rather than
+    // overrunning it.
+    EXPECT_EQ(nextScanDepth(100, 5, 5, 300), 300u);
+}
+
+TEST(VectorScan, ARaisedCapIsHonouredToo) {
+    // Not just lowering: an operator with a collection larger than 10000 rows
+    // raises it so a filtered sweep can be complete, which is the reason the
+    // setting exists at all.
+    EXPECT_EQ(firstScanDepth(500, 300, 50000), 50000u);
+    EXPECT_EQ(nextScanDepth(20000, 500, 1, 50000), 50000u);
+    EXPECT_GT(nextScanDepth(20000, 500, 1, 50000), kVectorFilterScanCap);
+}