Ver código fonte

fix(functions): refuse an unknown search option in the PRELUDE too

My previous commit fixed the HTTP /search route and left the function
surface open - and the function surface is the one that mattered. A
consumer answered the compatibility question by listing their call
sites, and every one of them was `ctx.collections(...).search`, with
nothing touching the HTTP route at all. Fixing only the route would have
looked finished while leaving the real callers exposed.

It is also the worse half. `.search()` and `.store()` build their
payload from an EXPLICIT key list, so an unrecognised option is
discarded in the prelude before the host can see it. A host-side check
is therefore no protection there: it cannot refuse what never arrives.
That is exactly how embedTimeoutMs came to be validated and honoured
host-side while the prelude never sent it, and a consumer was told a
bound was in force that was not - the comment warning about it is three
lines above the code that had the same hole.

mailOnlyKeys renamed to onlyKnownKeys, because the job is not mail's.

Tests use the file's existing expectRefused(), which also asserts the
host was NEVER REACHED - a refusal arriving after the search ran would
be no protection. Plus the falsifying half: every documented option on
both calls still passes, an explicitly `undefined` option is not a
misspelling (`{...partial, top_k: undefined}` is ordinary JS), and the
chained `.filter()` still merges with an explicit `filters` array rather
than one replacing the other.

All three consumers confirmed they send nothing outside the accepted
set, so this ships without breaking any of them.

Also records a lesson from one of them that generalises beyond this
change: a permissive test assertion's strength is a function of the
server's strictness, so tightening a contract can silently promote a lax
test elsewhere into a blind spot. Theirs used
expect.objectContaining({...}) on the outgoing body, which tolerates
extra keys by construction, so it could only fail in the direction that
was already safe. When asking consumers about a breaking change the
question is not only "do you send an extra key" but "would your tests
notice if you started".

1240/1240 green.
fszontagh 1 mês atrás
pai
commit
b8aafaa3a7
3 arquivos alterados com 117 adições e 4 exclusões
  1. 2 0
      CLAUDE.md
  2. 22 4
      runner/src/host_prelude.js
  3. 93 0
      runner/tests/host_prelude_test.cpp

+ 2 - 0
CLAUDE.md

@@ -48,6 +48,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - Filters: `field:op:value` (`op` ∈ eq/ne/gt/gte/lt/lte/in/contains/exists/regex/search). Used by `/documents` (`?filter=`, repeatable) **and** vector `/search` (`filters` body array) - both parse with `parseFilter()` and are evaluated by the DB, so semantics never diverge. `contains` is array membership; `search` is the substring op. Vector search intersects the DB's filter result with the similarity ranking (scores stay identical to an unfiltered query), scanning at most 10000 candidates.
 - **Embedding config precedence:** collection `embedding_model` pin → project override → global default; endpoint + API key are the project override when set, else global. Resolved by the pure `resolveEmbedding()` (`project_settings.hpp`) - unit-test precedence there, not through the handlers.
 - **Every outbound request to an external provider goes through `applyOutboundDefaults()`** (`outbound_http.hpp`): `User-Agent: smartbotic-vectorapi/<version>` and nothing else, TLS verification on, redirects off. Never let cpp-httplib's default UA reach a provider.
+- **A PERMISSIVE TEST ASSERTION'S STRENGTH DEPENDS ON THE SERVER'S STRICTNESS, so tightening a contract can silently promote a sloppy test elsewhere into a blind spot.** A consumer found this while checking whether the `unknown_option` refusal would break them: a test asserting their outgoing body with `expect.objectContaining({...})` tolerated extra keys by construction, so it could only ever fail in the direction that was already safe - add a stray key and the test stays green while production starts refusing every search with 422. They tightened it to an exact match. The lesson for asking consumers about a breaking change: the question is not only "do you send an extra key" but **"would your tests notice if you started"**.
 - **clangd, clang-format and clang-tidy are configured** (`.clangd`, `.clang-format`) and read `build-host/compile_commands.json`, so they cover `src/`, `tests/` and `runner/` including `runner/src/main.cpp`. The tidy set is narrow on purpose (`bugprone`/`cert`/`clang-analyzer`/`misc`/`performance`): the broad `modernize`/`readability` families bury real findings under thousands of style notes. `.clang-format` **describes the style the code already uses** rather than imposing one, so it is close to a no-op; `LambdaBodyIndentation: OuterScope` is the setting that matters, since every route handler is a lambda whose body is indented from the statement. Even so the codebase is hand-laid-out and not formatter-clean, so format **new or changed code only** (`git clang-format`), never whole files.
 - TS: no `any`, no TS `enum`, no constructor parameter-property shorthand (tsconfig `erasableSyntaxOnly`). Iterating parsed JSON: bind to a named var first (range-for over `nlohmann::json::parse(...)[...]` dangles).
 - Commits: conventional prefixes (`feat`/`fix`/`build`/`docs`/`test`). Branch for feature work; `main` is pushed to `ssh://git.smartbotics.ai:10022/fszontagh/smartbotic-vectorapi.git`.
@@ -65,6 +66,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **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.
 - **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.
+- **THE FUNCTION SURFACE NEEDED THE SAME FIX, AND NEEDED IT MORE.** `.search()`/`.store()` build their payload in `host_prelude.js` from an EXPLICIT key list, so an unrecognised option is discarded in the prelude **before the host can ever see it** - the host cannot refuse what never arrives, so a host-side check is no protection at all there. That is precisely how `embedTimeoutMs` came to be honoured host-side and never sent by the prelude while a consumer was told a bound was in force. `onlyKnownKeys()` (renamed from `mailOnlyKeys`, since the job is not mail's) now refuses by name in the prelude, and `expectRefused()` asserts the host was never reached rather than only that something threw. A consumer's call sites were ALL on this surface and none on the HTTP route, so fixing only the route would have left the real callers exposed while looking finished.
 - **An unknown key on a vector `/search` body is REFUSED (422 `unknown_option`), not ignored** (`functions/known_keys.hpp`, pure). It was ignored until 0.10.3, and measured on prod that produced silently wrong answers rather than errors: `topK: 3` returned the DEFAULT five rows, `minScore: 0.99` returned rows where the correct spelling returns none, and **`filter:` in the singular returned the rows the caller meant to EXCLUDE** - a dropped filter is frequently a tenancy boundary in the caller's mind, which is what makes this a defect and not an ergonomic wish. Every unrecognised key is named at once, and the accepted set is listed, because the usual cause is a plausible spelling of a real option. Matching is exact and case-sensitive on purpose: accepting `Top_K` would give the service two spellings for one option, which is how the next drift starts. `ctx.fetch`, `ctx.mail` and `ctx.jobs` already behaved this way; this brought the HTTP surface in line.
 - **`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.

+ 22 - 4
runner/src/host_prelude.js

@@ -197,6 +197,12 @@
       // dropping either set silently would widen the result.
       search: function (options) {
         need(options !== null && typeof options === 'object', '.search() takes an options object');
+        // Refused here, not host-side: the payload below is built from an
+        // explicit key list, so a misspelled option would be dropped before
+        // the host ever saw it. Measured over HTTP, where the same hole gave
+        // `topK` the DEFAULT top_k and a singular `filter` the rows the caller
+        // meant to exclude - both with a success status.
+        onlyKnownKeys(options, kSearchKeys, '.search()');
         const extra = options.filters === undefined || options.filters === null
                       ? [] : options.filters;
         need(Array.isArray(extra), '.search() filters must be an array of strings');
@@ -217,6 +223,7 @@
       },
       store: function (options) {
         need(options !== null && typeof options === 'object', '.store() takes an options object');
+        onlyKnownKeys(options, kStoreKeys, '.store()');
         // A stored vector is an inserted document, so it takes the same expiry
         // option an .insert() does - a cache of embeddings that cannot expire
         // is a cache that grows forever.
@@ -393,7 +400,18 @@
   const kMailReadKeys = ['host', 'port', 'user', 'userSecret', 'password', 'passwordSecret',
                          'tls', 'startTls', 'timeoutMs', 'mailbox', 'criteria', 'limit'];
 
-  function mailOnlyKeys(o, allowed, what) {
+  // Refuse an option name this surface does not take. Named for the job
+  // rather than for mail, which needed it first: the vector calls need it too,
+  // and for a sharper reason - their payload is built from an explicit key
+  // list, so an unrecognised key is DISCARDED here before the host can see it.
+  // The host therefore cannot refuse what never arrives, which is exactly how
+  // embedTimeoutMs came to be honoured by the host and never sent by the
+  // prelude while a consumer believed a bound was in force.
+  const kSearchKeys = ['query_text', 'query_vector', 'top_k', 'min_score', 'filters',
+                       'embedTimeoutMs'];
+  const kStoreKeys = ['text', 'vector', 'metadata', 'id', 'ttl_seconds', 'embedTimeoutMs'];
+
+  function onlyKnownKeys(o, allowed, what) {
     for (const key in o) {
       if (!Object.prototype.hasOwnProperty.call(o, key)) continue;
       if (o[key] === undefined) continue;
@@ -506,7 +524,7 @@
     // stated rather than assumed.
     read: function (options) {
       const o = opts(options, 'ctx.mail.read() options');
-      mailOnlyKeys(o, kMailReadKeys, 'ctx.mail.read()');
+      onlyKnownKeys(o, kMailReadKeys, 'ctx.mail.read()');
       const out = mailConnection(o, 'ctx.mail.read()');
       if (o.mailbox !== undefined && o.mailbox !== null) {
         need(typeof o.mailbox === 'string' && o.mailbox.length > 0,
@@ -534,7 +552,7 @@
     // a flat namespace, never "unknown".
     mailboxes: function (options) {
       const o = opts(options, 'ctx.mail.mailboxes() options');
-      mailOnlyKeys(o, kMailReadKeys, 'ctx.mail.mailboxes()');
+      onlyKnownKeys(o, kMailReadKeys, 'ctx.mail.mailboxes()');
       return __hostMail('mailboxes', mailConnection(o, 'ctx.mail.mailboxes()'));
     },
 
@@ -543,7 +561,7 @@
     // carries no Bcc and which a sender may make say anything.
     send: function (options) {
       const o = opts(options, 'ctx.mail.send() options');
-      mailOnlyKeys(o, kMailSendKeys, 'ctx.mail.send()');
+      onlyKnownKeys(o, kMailSendKeys, 'ctx.mail.send()');
       const out = mailConnection(o, 'ctx.mail.send()');
 
       need(typeof o.from === 'string' && o.from.length > 0,

+ 93 - 0
runner/tests/host_prelude_test.cpp

@@ -718,3 +718,96 @@ TEST(HostPrelude, AMailSendRefusesAnUnsendableMessageBeforeConnecting) {
                   "  attachments: [{ filename: 'x', base64: 'AAEC', text: 'y' }] });",
                   "ambiguous_body");
 }
+
+// --- unknown options on the VECTOR calls ----------------------------------
+//
+// These matter more than the HTTP equivalent, because the prelude builds the
+// payload from an explicit key list: an unrecognised option is DISCARDED here
+// before the host can see it, so the host cannot refuse what never arrives.
+// That is how embedTimeoutMs came to be honoured host-side and never sent by
+// the prelude, while a consumer believed a bound was in force.
+//
+// Measured over HTTP, where the same hole was open: `topK` returned the
+// DEFAULT top_k, and a singular `filter` returned the rows the caller meant to
+// EXCLUDE - both under a 200.
+
+TEST(HostPrelude, SearchRefusesAMisspelledOptionBeforeReachingTheHost) {
+    // expectRefused also asserts the host was never called, which is the
+    // property that matters: a refusal arriving after the search ran would be
+    // no protection at all.
+    expectRefused("ctx.collections('c').search({ query_text: 'x', topK: 3 });", "validation");
+    expectRefused("ctx.collections('c').search({ query_text: 'x', minScore: 0.9 });", "validation");
+}
+
+TEST(HostPrelude, SearchRefusesTheSingularFilterThatSilentlyWIDENEDTheResult) {
+    // The dangerous spelling: `filter` instead of `filters` dropped the filter
+    // and handed back the rows it existed to withhold.
+    expectRefused("ctx.collections('c').search({ query_text: 'x', filter: ['a:eq:b'] });",
+                  "validation");
+}
+
+TEST(HostPrelude, TheRefusalNamesTheOffendingKeyAndWhatIsAccepted) {
+    const nlohmann::json out =
+        runPrelude("ctx.collections('c').search({ query_text: 'x', topK: 3 });");
+    ASSERT_FALSE(out.at("threw").is_null()) << out.dump();
+    const std::string msg = out.at("threw").at("message").get<std::string>();
+    EXPECT_NE(msg.find("topK"), std::string::npos) << msg;
+    // The accepted set, because the usual cause is a plausible spelling of a
+    // real option rather than an invented one.
+    EXPECT_NE(msg.find("top_k"), std::string::npos) << msg;
+    EXPECT_NE(msg.find("min_score"), std::string::npos) << msg;
+}
+
+TEST(HostPrelude, StoreRefusesAnUnknownOptionToo) {
+    expectRefused("ctx.collections('c').store({ text: 'x', ttlSeconds: 60 });", "validation");
+}
+
+// --- and the falsifying half: everything documented must still pass --------
+
+TEST(HostPrelude, SearchStillAcceptsEveryDocumentedOption) {
+    // A refusal that refused everything would satisfy every test above while
+    // breaking every caller, so this is the one that makes them mean anything.
+    const nlohmann::json out = runPrelude(
+        "ctx.collections('c').search({ query_text: 'x', top_k: 3, min_score: 0.5,"
+        "  filters: ['a:eq:b'], embedTimeoutMs: 2000 });");
+    EXPECT_TRUE(out.at("threw").is_null()) << out.at("threw").dump();
+    EXPECT_EQ(out.at("calls").size(), 1u) << out.dump();
+}
+
+TEST(HostPrelude, SearchStillAcceptsAQueryVector) {
+    const nlohmann::json out =
+        runPrelude("ctx.collections('c').search({ query_vector: [0.1, 0.2], top_k: 1 });");
+    EXPECT_TRUE(out.at("threw").is_null()) << out.at("threw").dump();
+}
+
+TEST(HostPrelude, StoreStillAcceptsEveryDocumentedOption) {
+    const nlohmann::json out = runPrelude(
+        "ctx.collections('c').store({ text: 'x', metadata: { a: 1 }, id: 'i',"
+        "  ttl_seconds: 60, embedTimeoutMs: 2000 });");
+    EXPECT_TRUE(out.at("threw").is_null()) << out.at("threw").dump();
+}
+
+TEST(HostPrelude, AnEXPLICITLYUndefinedOptionIsNotAMisspelling) {
+    // `{ ...partial, top_k: undefined }` is ordinary JS for "not set", and
+    // must not read as a typo.
+    const nlohmann::json out = runPrelude(
+        "ctx.collections('c').search({ query_text: 'x', top_k: undefined,"
+        "  min_score: undefined });");
+    EXPECT_TRUE(out.at("threw").is_null()) << out.at("threw").dump();
+}
+
+TEST(HostPrelude, TheChainedFilterStillMergesWithAnExplicitFiltersArray) {
+    // The refusal must not have broken the merge: `.filter()` on the chain and
+    // `filters:` in the call are APPENDED, never one replacing the other.
+    const nlohmann::json out = runPrelude(
+        "ctx.collections('c').filter('x:eq:1').search({ query_text: 'q',"
+        "  filters: ['y:eq:2'] });");
+    EXPECT_TRUE(out.at("threw").is_null()) << out.at("threw").dump();
+    // onlyCall returns the recorded ARGS: (collection, op, payload).
+    const nlohmann::json args = onlyCall(out, "db");
+    ASSERT_GE(args.size(), 3u) << args.dump();
+    const nlohmann::json& sent = args.at(2).at("filters");
+    EXPECT_EQ(sent.size(), 2u) << sent.dump();
+    EXPECT_EQ(sent.at(0), "x:eq:1") << sent.dump();
+    EXPECT_EQ(sent.at(1), "y:eq:2") << sent.dump();
+}