Kaynağa Gözat

fix: five defects, one of them silent data loss on vector collections

The worst of these destroys data. A whole-document PUT on a vector
collection discarded the stored embedding: the call returned success and
the document stopped being searchable. The caller could not prevent it,
because no read returns the vector, so a read-modify-write had nothing
to put back. Measured on a 12448-row collection - a merge PATCH
preserves the vector, an update drops it. Now refused with 422
vector_replace_unsafe unless the body carries a vector, naming PATCH and
the vectors route as the two ways through.

The other four came from a consumer, and all four were real:

- A transient database failure surfaced as 404 "no such collection",
  which cost them a 6-minute ingest. Client::get returns nullopt for
  both absence and transport failure, so the registry could not tell
  them apart, and a 404 is correctly unretryable for a careful client.
  CollectionRegistry::get now retries once (logging when the retry
  succeeds) and asks healthCheck() before reporting absence, throwing
  503 when the database is unreachable.

- A filtered vector search could silently return fewer hits than match:
  455 of 553 true matches on that same collection, because the walk
  goes only 10000 candidates deep. The response now carries
  scan_capped/scanned, set only when the walk hit the cap while short
  of top_k and the ranking was not exhausted, so a filter that merely
  matches less than top_k is still reported as complete.

- A scoped key could not enumerate collections. Listing is not
  managing, so list and GET-one now take requireProjectAccess.

- There was no way to ask the running server its version.

Also: embedTimeoutMs never worked. The host validated and honoured it,
but the prelude built its payload from an explicit key list that omitted
it, so every value was accepted and dropped - which is exactly why an
unsupported option must be refused rather than ignored. A ctx.fetch
timeout is now reported as fetch_timeout (504) rather than folded into
fetch_failed, with the budget and elapsed time logged.

Collection delete drops the collection's indexes and its vector index
explicitly, and the create-time repair is gated on whether anything is
still attached to the name rather than on getCollectionInfo - a poisoned
name has no collection, so a presence check skipped the repair in
exactly the case that needed it.

The docs were revalidated against the sources. llms.txt was missing
three ctx.* surfaces, the non-HTTP ctx shape, the cron/db/job triggers
and about twenty error slugs; openapi's Error schema was flat while
every error body is nested, so a generated client read error as a
string. Three of the corrected lines were written earlier the same day:
enqueue returns a bare string, ifVersion is update/patch only, and
details carries field/fields/values rather than value.
fszontagh 1 ay önce
ebeveyn
işleme
ea114ba0fa

+ 2 - 0
CLAUDE.md

@@ -107,6 +107,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`patch` with a field set to null REMOVES the field** (RFC 7396 merge), it does not store null. Use `update` for an explicit null.
 - **Null and absent are both unconstrained on a unique index** since database 2.12.0 - only real values collide. Before that, two nulls collided.
 - **`relations_enforced` is readable since client 2.11.4** via `tryGetRelationsEnforced()`, which DECLINES to answer on a failed read rather than defaulting (`getRelationsEnforced()` is the fail-to-enforced variant, for code deciding whether it may rely on enforcement). The collection GET surfaces it, omitting the field when undetermined - absence never means disabled, so the web UI renders three states, not two.
+- **`Client::get` returns nullopt for BOTH "absent" and "transport failed"** - it throws only for PERMISSION_DENIED - so a registry lookup cannot tell them apart from the return value. Unhandled, that reaches a caller as 404 "no such collection" for a collection that exists, and a 404 is unretryable BY DESIGN for a careful client, because adding it to a retry set would retry every genuine absence. A consumer lost a 6-minute ingest of an 8 GB mailbox to exactly this. `CollectionRegistry::get` therefore **retries once** (a transient failure usually succeeds, and logs a warning saying so) and then asks `healthCheck()` before reporting absence, throwing **503** when the database is unreachable. Reported upstream too: the client should distinguish, the way it already does for a permission denial.
+- **A filtered vector search can return FEWER hits than match, and the response now says so.** The walk goes only `kVectorFilterScanCap` (10000) deep into the ranking, so on a larger collection a filter whose matches lie deeper is silently short - measured at 455 returned of 553 true matches on 12448 rows. `VectorSearchResult::scanCapped` is set ONLY when the walk hit the cap while still short of `topK` and the ranking was not exhausted, so a filter that merely matches fewer rows than `top_k` is correctly reported as complete rather than crying wolf. The HTTP route adds `scan_capped`/`scanned`; `ctx...search()` keeps its ARRAY return and warns in the run console instead.
 - **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, or `duplicate_id` when `reason` says so (database 2.12.1: a taken document id and a taken unique field value are the same code but different remedies), FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
 - **QuickJS is pinned to an exact quickjs-ng tag** (`SVAPI_QUICKJS_TAG`, `runner/CMakeLists.txt`). QuickJS bytecode carries **no version stamp**, so a silent upgrade makes a cached blob *misread* rather than fail. quickjs-ng, not Bellard's tree: the module/promise/stack entry points the core needs (`JS_GetModuleNamespace`, `JS_PromiseState`, `JS_SetMaxStackSize`, `JS_IsJobPending`) are public API there. `JsBytecode` is an in-process cache only - never persist it without a QuickJS build fingerprint.

+ 28 - 5
api/llms.txt

@@ -67,14 +67,16 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
 - `POST  /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` or `{...}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
 
-  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: `field`, the colliding `value` when that field is at the top level of the body you sent, and `conflicting_document_id` (the document already holding it). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
+  **Other slugs worth branching on.** From the database: `read_only` **503** (the database is refusing writes), `db_unavailable` **503**, `rate_limited` **429** raised by the DATABASE under pressure (distinct from a key's scope rate limit, same status), `internal` **500**. On the routes: `exists` **422** (duplicate collection name), `bad_project` **422**, `last_admin` **422** (refusing to remove the last admin key), `not_vector` **422** (a vector op on a json collection), `dimension_mismatch` **422**, `ambiguous_body` **422**, `file_too_large` **422**, `vector_replace_unsafe` **422**. On `/fn/*`: `function_error` **500** and `method_not_allowed` **405**. On function writes: `no_runner` and `runner_unreachable` both **503**; invoke answers **409** `function_invalid` or `function_disabled`. Inside a function: `jobs_unavailable` **503**, `job_depth_exceeded` **422**, `unsupported_combination` **422**, `body_too_large` **422**, `not_json` **422**, `embedding_timeout` **504**, `fetch_timeout` **504**.
+
+  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: **`field`** when one field collided or **`fields`** when several, **`values`** (an OBJECT of the colliding field/value pairs, not a bare `value`), `conflicting_document_id` (the document already holding it), and `relation` or `current_version` where they apply. A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing collection is **404** only when its absence is CONFIRMED: if the database cannot be reached the answer is **503**, never a 404, so a 404 is always safe to treat as definitive and unretryable. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write. **On a `kind=vector` collection, a PUT whose body carries no vector is refused **422** `vector_replace_unsafe`.** A replace discards the stored embedding and the caller cannot prevent it, because no read returns the vector - so there is nothing to put back. Use `PATCH` for fields, or `POST .../vectors` to store a document together with its vector.
 
   **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
 - `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. PUT does not take `?ttl_seconds=`; use POST with an `id` to create with an expiry.
 - `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
 
-  **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` and is not available on a `kind=vector` collection (**422** `conditional_unsupported` for both): the version-checked write has no expiry field, and it rewrites the whole document, which would drop the stored embedding.
+  **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.
 - `POST  /api/v1/projects/{project}/collections/{name}/documents/{id}/increment` `{field: n, ...}` (or `{data:{...}}`) - **Atomic increment.** Adds each number to the named field in ONE locked server-side read-modify-write, so concurrent increments cannot lose each other. Dotted keys address nested fields (`counts.sent`). Returns **200** `{id, values}` where `values` holds the NEW value of every field you named. An absent or null field counts as 0. Integer + integer stays an integer (overflow is refused); anything else becomes a double. A field holding a non-number is **422** `validation` and **nothing at all is applied** - the whole set applies or none of it does. Needs the `update` grant (it is a write, so a read-only scope gets **403**); it is a separate route rather than a flag on PATCH because `{"calls":1}` means "set calls to 1" on PATCH and "add 1 to calls" here.
 
   **It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
@@ -125,7 +127,7 @@ Relation names are per-project and **unqualified**: requests and responses alway
 Requires a `kind=vector` collection. Vectors are stored with cosine-similarity indexing.
 
 - `POST /api/v1/projects/{project}/collections/{name}/vectors` `{id?, text?, vector?, metadata?}` - Store a vector. Supply either `text` (the server embeds it, resolving the model as: the collection's `embedding_model` pin, else the project's embedding override, else the global default) or a pre-computed `vector` array. `vector` dimension must match the collection's `vector_dimension`. `metadata` is an arbitrary JSON object stored alongside the vector.
-- `POST /api/v1/projects/{project}/collections/{name}/search` `{query_text?, query_vector?, top_k?, min_score?, filters?}` - Cosine-similarity search. Supply either `query_text` or `query_vector`; neither is **422**. `top_k` caps the results, **default 5**. `min_score` (0-1) drops low-confidence matches, default 0. `filters` is an array of `field:op:value` strings applied to the vector's metadata, using the grammar and operators above - metadata is stored at the top level of the document, so a vector written with `metadata:{"colour":"red"}` is filtered as `colour:eq:red`.
+- `POST /api/v1/projects/{project}/collections/{name}/search` `{query_text?, query_vector?, top_k?, min_score?, filters?}` - Cosine-similarity search. Supply either `query_text` or `query_vector`; neither is **422**. `top_k` caps the results, **default 5**. `min_score` (0-1) drops low-confidence matches, default 0. `filters` is an array of `field:op:value` strings applied to the vector's metadata, using the grammar and operators above - metadata is stored at the top level of the document, so a vector written with `metadata:{"colour":"red"}` is filtered as `colour:eq:red`. The response also carries **`scan_capped`** (and `scanned`, plus `scan_cap` when capped): a filtered search walks the ranking only `scan_cap` deep, so on a collection larger than that a filter whose matches lie deeper returns FEWER hits than match. `scan_capped: false` means the answer is complete - including the ordinary case of a filter matching fewer rows than `top_k`. **Check it before treating a filtered result set as exhaustive.** Inside a function the return stays an array and the warning goes to the run's console instead.
 
   Filtering is evaluated by the database, then intersected with the similarity ranking, so scores are identical with and without a filter and `min_score` means the same thing either way. The scan is bounded at 10000 candidates: within a collection of that size a filtered search returns exactly the true top-k, and beyond it a filter matching only very low-ranked vectors may return fewer.
 
@@ -135,6 +137,8 @@ Requires a `kind=vector` collection. Vectors are stored with cosine-similarity i
 
 ## Settings (admin)
 
+`PUT /api/v1/settings` also accepts **`function_egress_blocked_cidrs`** (an array of CIDRs, **422** `invalid_cidr` on a bad one) and **`function_egress_allow_private`** (a bool). The blocklist is **UNIONED** with the built-in defaults, never substituted for them, and `function_egress_allow_private` relaxes ONLY the private ranges - the metadata endpoint, link-local, multicast and the IPv6 spellings of an IPv4 address stay blocked whatever it is set to. **`max_file_bytes` is returned by GET but is NOT settable over the API**; it is read from the stored settings document.
+
 All settings endpoints require an admin key.
 
 - `GET  /api/v1/settings` - Return current settings as JSON. `openai_api_key` is masked: the field is absent and `openai_api_key_set` (bool) indicates whether a key is configured.
@@ -198,7 +202,7 @@ Server-side JavaScript that serves HTTP routes. These routes require a key grant
 A function is an ES module exporting a trigger declaration and a default handler:
 
 ```js
-export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
+export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }; **`type` is `http` (the default), `cron`, `db` or `job`.** `cron` needs `schedule` (five-field) and optionally `tz`, an IANA zone validated against the host's time-zone database at PUSH time - an unknown zone is refused, never silently UTC. `db` needs `table` and `event` (INSERT/UPDATE/DELETE). `job` is reached only by being enqueued. **`singleFlight` defaults to TRUE for cron** and false otherwise.
 
 export default async function (ctx) {
   const docs = await ctx.collections('kb_chunks')
@@ -215,14 +219,32 @@ 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.
+- **Write options**, previously undocumented. `ttl_seconds` is accepted by `.insert()`, `.update()`, `.patch()` and `.store()`; it sets or clears a document's expiry, and **absent is not zero** - omitting it leaves an existing expiry untouched while `0` clears it, so a plain `.patch()` cannot accidentally make a temporary document permanent. **`ifVersion: n`** makes the write conditional on the document still being at version `n` (as returned in `_version`); a lost race is **409** `version_conflict` carrying `current_version`, which means "someone else has it" and should be handled by dropping the work or re-reading, never by retrying the same write. `ifVersion` must be a positive integer - version 0 does not exist, since a first write produces 1. It is accepted by **`.update()` and `.patch()` only**: `.insert()` refuses it by name, because there is no existing version for a document that does not yet exist. `ttl_seconds` together with `ifVersion` is refused (`unsupported_combination`) rather than silently dropping one. A conditional `.update()` returns `{id, version}`; the unconditional form returns `{id}`.
 - 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, 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}`.
+- **The `ctx.fetch` response** carries `status`, `headers`, `body`, `bodyEncoding` and a `res.json()` helper. `res.json()` on a base64 response throws `not_json` rather than parsing bytes as text.
+- `ctx.files.list()` returns at most **100** entries and does not page. `ctx.crypto.hmacSha256` accepts `{base64:'...'}` for either `key` or `data`, not only strings.
+- `.insert(doc)` honours an **`id` inside the document object** - the idiom for an idempotent write.
+- `.store()` also accepts `id` and `ttl_seconds`. A `.filter(...)` accumulated on the chain is **appended** to an explicit `filters` array in `.search({...})`, never replaced by it.
+- `ctx.jobs.enqueue(functionId, payload, options?)` - put work on the job queue, returning the **job id as a plain string** (not an object). The project is NOT an argument: a function enqueues into its own project or not at all. **This is where slow work belongs** - a job run gets the job wall ceiling (far higher than an HTTP run's) and draws from its own pool lane, so it cannot starve interactive routes. Options: `runAt` (a `Date` or epoch milliseconds) **or** `delaySec`, never both - reconciling them would be a guess at what the author meant, so it is **422** `ambiguous_body`; and `dedupeKey`, a non-empty string of at most 512 characters that collapses repeated enqueues of the same logical work. An unknown option name is refused **by name** rather than ignored.
+- `ctx.jobs.cancel(id)` - cancel a job that has not been claimed yet. Returns a **boolean**: false when there was nothing cancellable.
+- **Job delivery is at-least-once.** A claim that goes stale is reclaimed and the job runs AGAIN, so anything reached by a job, a cron or a database event must be idempotent. A function that throws is NOT retried (one attempt, the author's to fix); what re-runs work is reclaim. See the error table above for `version_conflict`, which is how a conditional claim reports losing the race.
+- `ctx.crypto.hmacSha256(key, data, encoding?)` - HMAC-SHA256, `encoding` being `hex` (default) or `base64`. For verifying a provider's webhook signature.
+- `ctx.crypto.timingSafeEqual(a, b)` - constant-time string comparison. Use it to compare a signature rather than `===`, which leaks the position of the first difference.
+- `ctx.crypto.randomUUID()` - a version 4 UUID.
+- `ctx.time.parts(epochMs, zone)` - civil fields for an instant in an IANA zone: `{year, month, day, hour, minute, second, weekday, offsetSec, zone}`. Available without `Intl` having to be loaded.
+- `ctx.time.fromParts(parts, zone)` - the reverse. It reports a local time that does not exist (the DST spring-forward gap) rather than inventing one, and tells you when a local time is ambiguous (the autumn repeat).
+- `ctx.time.zoneKnown(zone)` - whether the host's time-zone database knows that name. An unknown zone is a catchable error everywhere else, never a silent fall back to UTC.
+- `ctx.time.format(epochMs, zone, pattern, locale?)` - format an instant, e.g. `format(ms, 'Europe/Budapest', 'YYYY. MMMM D., dddd', 'hu')`. An unknown locale is refused rather than served in English.
+- `Intl.DateTimeFormat` also works inside a function, installed per context.
 - **`responseType: 'base64'` returns a BINARY response body** as base64. Needed for anything that is not text: the value handed to the engine is serialised as JSON, and a JSON string cannot hold a byte outside a valid UTF-8 sequence, so a non-text body is either base64 or it is refused. The refusal names this fix rather than surfacing a raw UTF-8 decode error.
 - **`timeoutMs` narrows the call, never widens it**, and is capped by what is left of the run's budget. There is no connection pooling: every call builds its own client, so there is no keep-alive socket to go stale.
 - **Exceeding the budget is 504 `fetch_timeout`, not `fetch_failed`.** The connect, read and write timeouts are set to the run's REMAINING budget, so a provider slower than that is cut off by us - and the underlying library words that as "Failed to read connection", which reads like a network fault. The error says how long the call took and how long it was allowed, so the two are distinguishable. A long provider call belongs on a **job** trigger, whose ceiling is far higher than an HTTP run's.
-- Sending a binary REQUEST body is not supported yet: `body` is a string.
+- **Sending a BINARY request body is supported** - this was previously undocumented, and a consumer concluded it was missing. `body` is text (a JS string). For bytes use **`bodyBase64`** (a base64 string, decoded before sending) or **`bodyBytes`** (an array of 0-255 integers). Exactly ONE of the three, never two: supplying both is refused with `ambiguous_body` rather than resolved by precedence, because reading `body` and ignoring a `bodyBase64` beside it would silently send the wrong payload. Invalid base64 is **422**.
+- **`Content-Type` is defaulted to `application/json` only for the TEXT shape.** A binary body is never given a default: labelling arbitrary bytes as JSON would be a lie a provider then rejects or mis-parses, so a caller sending bytes must say what they are.
 - `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.
 
@@ -269,6 +291,7 @@ export default async function (ctx) {
 
 Public (no auth required):
 
+- `GET /version` and `GET /api/v1/version` - `{name, version, commit, db_client}`. The root one needs **no credential**; the `/api/v1` one needs any valid key (a scoped key is fine), because everything under `/api/` is authenticated. Ask it rather than probing a behaviour to work out which server you are talking to.
 - `GET /healthz` - Liveness probe; always 200 while the process is running.
 - `GET /readyz`  - Readiness probe; 200 when the database is reachable, 503 otherwise.
 - `GET /openapi.json` - OpenAPI 3.1 machine-readable spec.

+ 149 - 62
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.7.1",
+    "version": "0.8.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -123,7 +123,7 @@
     "schemas": {
       "FunctionDescriptor": {
         "type": "object",
-        "description": "The validated `on` block the script exports. Server-held: it is whatever the runner parsed out of the source, never sent by a client.",
+        "description": "The `on` block a function exports. Unknown keys are ignored so a script written for a later server still loads, and a parse failure is data rather than an exception.",
         "properties": {
           "id": {
             "type": "string",
@@ -134,9 +134,10 @@
             "enum": [
               "http",
               "cron",
-              "db"
+              "db",
+              "job"
             ],
-            "description": "Only `http` is dispatched in this release; the others parse so a newer script gets a clear message rather than being treated as a route."
+            "description": "What starts a run. `http` serves a route under /fn/{project}/. `cron` fires on a schedule. `db` fires on an INSERT/UPDATE/DELETE in a watched collection. `job` is reached only by being enqueued, which is where slow work belongs."
           },
           "route": {
             "type": "string",
@@ -151,11 +152,11 @@
           },
           "schedule": {
             "type": "string",
-            "description": "Cron trigger: validated for shape only; nothing schedules it yet"
+            "description": "Five-field cron expression, required for `type: cron`. With `tz`, an IANA zone validated against the host's time-zone database at PUSH time - an unknown zone is refused, never silently UTC."
           },
           "table": {
             "type": "string",
-            "description": "Database trigger: the collection watched"
+            "description": "Watched collection, required for `type: db`."
           },
           "event": {
             "type": "string",
@@ -163,14 +164,20 @@
               "INSERT",
               "UPDATE",
               "DELETE"
-            ]
+            ],
+            "description": "Required for `type: db`."
           },
           "timeoutMs": {
             "type": "integer",
             "description": "Declared wall-clock budget. Omitted when the script did not declare one; a declared value is still clamped to the runner's configured maximum."
           },
           "singleFlight": {
-            "type": "boolean"
+            "type": "boolean",
+            "description": "Skip a tick while the previous run is still going. Defaults to TRUE for cron and false otherwise."
+          },
+          "tz": {
+            "type": "string",
+            "description": "IANA zone for a cron schedule, validated at push time."
           }
         },
         "required": [
@@ -428,18 +435,32 @@
       },
       "Error": {
         "type": "object",
+        "required": [
+          "error"
+        ],
         "properties": {
           "error": {
-            "type": "string"
-          },
-          "message": {
-            "type": "string"
+            "type": "object",
+            "required": [
+              "code",
+              "message"
+            ],
+            "properties": {
+              "code": {
+                "type": "string",
+                "description": "Stable machine-readable slug. Branch on THIS, never on the message."
+              },
+              "message": {
+                "type": "string"
+              },
+              "details": {
+                "type": "object",
+                "additionalProperties": true,
+                "description": "Present on some errors. For a duplicate: `field` (one) or `fields` (several), `values` (an object of colliding field/value pairs), `conflicting_document_id`, and `relation`/`current_version` where they apply."
+              }
+            }
           }
-        },
-        "required": [
-          "error",
-          "message"
-        ]
+        }
       },
       "CollectionMeta": {
         "type": "object",
@@ -467,6 +488,14 @@
           },
           "created_at": {
             "type": "integer"
+          },
+          "document_count": {
+            "type": "integer",
+            "description": "Live count, added by both collection reads."
+          },
+          "size_bytes": {
+            "type": "integer",
+            "description": "Live size, added by both collection reads."
           }
         },
         "required": [
@@ -631,6 +660,7 @@
                     "code": {
                       "type": "string",
                       "enum": [
+                        "duplicate_id",
                         "duplicate_values",
                         "relation_restricted",
                         "version_conflict"
@@ -822,7 +852,7 @@
         }
       ],
       "get": {
-        "summary": "Get project info (collection and document counts)",
+        "summary": "One project with its collection count",
         "operationId": "getProject",
         "responses": {
           "200": {
@@ -836,10 +866,8 @@
                       "type": "string"
                     },
                     "collections": {
-                      "type": "integer"
-                    },
-                    "documents": {
-                      "type": "integer"
+                      "type": "integer",
+                      "description": "How many collections the project has. No document count is returned here - use /stats."
                     }
                   }
                 }
@@ -868,10 +896,13 @@
             "description": "Unauthorized"
           },
           "403": {
-            "description": "Forbidden - admin required or cannot drop default"
+            "description": "Forbidden - admin required"
           },
           "404": {
             "description": "Project not found"
+          },
+          "422": {
+            "description": "Refusing to drop the `default` project (`protected`)"
           }
         }
       }
@@ -2021,7 +2052,7 @@
             "description": "Validation error (fields missing, repeated, or naming fewer than two fields)"
           },
           "503": {
-            "description": "The database did not apply the drop"
+            "description": "The database did not apply the drop (`unavailable`)"
           }
         }
       },
@@ -2256,8 +2287,8 @@
           "403": {
             "description": "Forbidden - project access required; scoped keys cannot manage indexes"
           },
-          "404": {
-            "description": "Index not found"
+          "503": {
+            "description": "The database did not apply the drop (`unavailable`)"
           }
         }
       }
@@ -2622,11 +2653,25 @@
                           "score": {
                             "type": "number"
                           },
-                          "metadata": {
-                            "type": "object"
+                          "data": {
+                            "type": "object",
+                            "additionalProperties": true,
+                            "description": "The stored document. Named `data`, not `metadata`. The stored vector is NOT included - no read returns it."
                           }
                         }
                       }
+                    },
+                    "scan_capped": {
+                      "type": "boolean",
+                      "description": "True when the filtered walk stopped at the candidate scan cap while still short of top_k, so MORE rows may match than were returned. False means the answer is complete, including a filter that simply matches fewer rows than top_k. Check it before treating a filtered result set as exhaustive."
+                    },
+                    "scanned": {
+                      "type": "integer",
+                      "description": "How deep into the ranking the walk went. Absent for an unfiltered search."
+                    },
+                    "scan_cap": {
+                      "type": "integer",
+                      "description": "The cap that was hit. Present only when scan_capped is true."
                     }
                   }
                 }
@@ -4197,48 +4242,23 @@
                 "schema": {
                   "type": "object",
                   "properties": {
-                    "projects": {
+                    "total_collections": {
                       "type": "integer"
                     },
-                    "memory_pressure_level": {
+                    "total_documents": {
                       "type": "integer"
                     },
-                    "collections": {
+                    "memory_used_bytes": {
                       "type": "integer"
                     },
-                    "documents": {
-                      "type": "integer"
-                    },
-                    "embedding": {
-                      "type": "object",
-                      "properties": {
-                        "cache_size": {
-                          "type": "integer"
-                        },
-                        "cache_capacity": {
-                          "type": "integer"
-                        },
-                        "cache_hits": {
-                          "type": "integer"
-                        },
-                        "cache_misses": {
-                          "type": "integer"
-                        },
-                        "cache_hit_ratio": {
-                          "type": "number"
-                        },
-                        "cache_bytes": {
-                          "type": "integer"
-                        }
-                      }
+                    "memory_pressure_percent": {
+                      "type": "number"
                     },
-                    "db_client_version": {
-                      "type": "string",
-                      "description": "Version of the smartbotic-database client library actually bound by the dynamic linker at process startup - not necessarily the version this binary was compiled against. 2.4.x and 2.11.x share a SONAME, so a mismatched shared library can load silently at runtime and only surface as a crash on a later restart; this field lets an operator catch that before it does."
+                    "insert_count": {
+                      "type": "integer"
                     },
-                    "db_client_commit": {
-                      "type": "string",
-                      "description": "Commit hash of the loaded smartbotic-database client library, for the same reason as db_client_version."
+                    "query_count": {
+                      "type": "integer"
                     }
                   }
                 }
@@ -4639,6 +4659,73 @@
           }
         }
       }
+    },
+    "/version": {
+      "get": {
+        "summary": "The running server's version",
+        "description": "Needs no credential - a version string is not a secret, and a client that cannot ask has to probe a behaviour to find out which server it is talking to.",
+        "responses": {
+          "200": {
+            "description": "Version info",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "name": {
+                      "type": "string"
+                    },
+                    "version": {
+                      "type": "string"
+                    },
+                    "commit": {
+                      "type": "string"
+                    },
+                    "db_client": {
+                      "type": "string"
+                    }
+                  }
+                }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/version": {
+      "get": {
+        "summary": "The running server's version",
+        "description": "Needs any valid key; everything under /api/ is authenticated.",
+        "responses": {
+          "200": {
+            "description": "Version info",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "name": {
+                      "type": "string"
+                    },
+                    "version": {
+                      "type": "string"
+                    },
+                    "commit": {
+                      "type": "string"
+                    },
+                    "db_client": {
+                      "type": "string"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "401": {
+            "description": "Unauthorized"
+          }
+        }
+      }
     }
   }
 }

+ 14 - 5
runner/src/host_context.cpp

@@ -1367,13 +1367,22 @@ 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 std::vector<smartbotic::database::Client::SimilarityResult> results =
-            vectorSearch(db.client(), c, q, topK, minScore, filters);
+        const VectorSearchResult found = vectorSearch(db.client(), c, q, topK, minScore, filters);
+
+        // An incomplete answer is said out loud in the run's console rather
+        // than added to the return value: the return stays an ARRAY, which is
+        // what the design's example reads and what every existing script
+        // indexes into. A field would mean changing that shape for everyone to
+        // carry a flag almost no run needs - at the top_k of 5-10 a function
+        // actually uses, the cap is never reached.
+        if (found.scanCapped)
+            addLog("[warn] search on '" + collection + "' stopped at the " +
+                   std::to_string(kVectorFilterScanCap) +
+                   "-candidate scan cap while still short of top_k " +
+                   std::to_string(topK) + ": more rows may match than were returned");
 
-        // An array, not {results:[...]}: the design's own example reads the
-        // return value as the hits.
         nlohmann::json out = nlohmann::json::array();
-        for (const auto& r : results)
+        for (const auto& r : found.hits)
             out.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
         return out;
     }

+ 8 - 0
runner/src/host_prelude.js

@@ -204,6 +204,13 @@
           query_vector: options.query_vector,
           top_k: options.top_k,
           min_score: options.min_score,
+          // Passed through, NOT dropped. This payload is built from an explicit
+          // key list, so an option missing from the list is silently discarded
+          // before the host ever sees it - which is what happened to
+          // embedTimeoutMs: the host validated and honoured it, the prelude
+          // never sent it, and a consumer was told a bound was in force that
+          // was not. Any option added here must be added to this list too.
+          embedTimeoutMs: options.embedTimeoutMs,
           filters: query.filters.concat(extra)
         });
       },
@@ -221,6 +228,7 @@
           vector: options.vector,
           metadata: options.metadata,
           id: options.id,
+          embedTimeoutMs: options.embedTimeoutMs,
           ttl_seconds: ttl
         });
       }

+ 38 - 2
src/collection_registry.cpp

@@ -1,4 +1,9 @@
 #include "collection_registry.hpp"
+
+#include "errors.hpp"
+
+#include <spdlog/spdlog.h>
+
 #include <ctime>
 
 namespace svapi {
@@ -39,8 +44,39 @@ bool CollectionRegistry::add(const std::string& project, const CollectionMeta& m
 
 std::optional<CollectionMeta> CollectionRegistry::get(const std::string& project,
                                                        const std::string& name) {
-    if (auto doc = db_.client().get(coll(project), name))
-        return CollectionMeta::fromJson(*doc);
+    const std::string c = coll(project);
+    if (auto doc = db_.client().get(c, name)) return CollectionMeta::fromJson(*doc);
+
+    // An empty answer from the client is AMBIGUOUS: `Client::get` returns
+    // nullopt both for "no such document" and for a transport failure, which it
+    // only logs. (It throws for PERMISSION_DENIED precisely so a denial cannot
+    // look like no data; the same reasoning was never extended to UNAVAILABLE.)
+    //
+    // Left alone, that ambiguity reaches a caller as 404 "no such collection"
+    // for a collection that exists - and a 404 is unretryable BY DESIGN for a
+    // careful client, because adding it to a retry set would retry every
+    // genuine absence. A consumer lost a 6-minute ingest of an 8 GB mailbox to
+    // exactly this, and the collection was present before and after.
+    //
+    // So: ask again. A genuine absence answers nullopt twice and costs one
+    // cheap registry read on a path that was already going to 404. A transient
+    // failure almost always succeeds on the second call, which is both the
+    // correct answer AND cheaper for the caller than a retryable error.
+    if (auto retried = db_.client().get(c, name)) {
+        spdlog::warn("registry lookup for {}:{} failed once and succeeded on retry - a transient "
+                     "database failure was about to be reported as 'no such collection'",
+                     project, name);
+        return CollectionMeta::fromJson(*retried);
+    }
+
+    // Still empty. Either it really is absent, or the database is properly
+    // down - and those must not share an answer. healthCheck() is the only
+    // thing that can tell them apart here, and it is asked ONLY on this path,
+    // so a hot lookup never pays for it.
+    if (!db_.client().healthCheck())
+        throw ApiError(ErrCode::Unavailable, "db_error",
+                       "cannot determine whether collection '" + name +
+                           "' exists: the database is not reachable");
     return std::nullopt;
 }
 

+ 13 - 2
src/handlers/collections.cpp

@@ -79,7 +79,14 @@ void registerCollectionRoutes(ApiServer& s) {
 
     svr.Get(R"(/api/v1/projects/([^/]+)/collections)", [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req); std::string project = req.matches[1];
-        requireProjectManage(k, project);
+        // Project ACCESS, not project-manage: enumerating is not managing.
+        // A scoped key could already read every document in a collection but
+        // could not learn that the collection existed, which forced a consumer
+        // to hardcode four collection names into a backup script - so a
+        // collection added later was silently missed by the backup, exactly
+        // the failure a listing prevents. Create, alter and drop stay behind a
+        // full key below.
+        requireProjectAccess(k, project);
 
         auto lower = [](std::string s) {
             std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); });
@@ -130,7 +137,11 @@ void registerCollectionRoutes(ApiServer& s) {
 
     svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req); std::string project = req.matches[1], name = req.matches[2];
-        requireProjectManage(k, project);
+        // Project ACCESS, matching the LIST route above: a scoped key that can
+        // enumerate collections must also be able to read one's metadata, or it
+        // can see a name and nothing about it. Create, alter and drop stay
+        // behind a full key.
+        requireProjectAccess(k, project);
         auto m = d->registry.get(project, name);
         if (!m) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
         nlohmann::json e = m->toJson();

+ 22 - 0
src/handlers/documents.cpp

@@ -186,6 +186,28 @@ void registerDocumentRoutes(ApiServer& s) {
         const auto ifVersion = ifVersionParam(req);
         nlohmann::json data = documentBody(bodyJson(req));
 
+        // A REPLACE on a vector collection destroys the stored embedding, and
+        // the caller cannot prevent it.
+        //
+        // Measured: on a kind=vector collection a merge PATCH preserves the
+        // vector, while a whole-document update drops it - the call returns
+        // success and the document stops being searchable. The database
+        // consumes `_vector` into its index on write and returns it from
+        // nothing (not get, not find, not similaritySearch), so a caller doing
+        // read-modify-write CANNOT put it back: there is no way to read it.
+        // That makes PUT an embedding-destroying operation that looks like an
+        // ordinary write, on data that cost money to produce.
+        //
+        // So refuse it unless the body carries a vector, and name both ways
+        // out. Not a silent repair: re-embedding here would spend the
+        // project's embedding credit on a request that never asked for it.
+        if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector"))
+            throw ApiError(ErrCode::Unprocessable, "vector_replace_unsafe",
+                           "replacing a document in a vector collection would discard its stored "
+                           "embedding, which cannot be read back to include here. Use PATCH to "
+                           "change fields without touching the vector, or POST .../vectors to "
+                           "store a document together with its vector");
+
         // PUT creates the document when it is absent, which is what the method
         // means and what this API has always documented. The alternative - 404
         // plus a separate upsert route - would give PUT a meaning HTTP does not

+ 22 - 0
src/handlers/meta.cpp

@@ -1,5 +1,6 @@
 #include "json_http.hpp"
 #include "server.hpp"
+#include "svapi/version.hpp"
 #include <fstream>
 #include <sstream>
 
@@ -19,6 +20,27 @@ void registerMetaRoutes(ApiServer& s) {
         else sendJson(res, 503, {{"status", "unavailable"}});
     });
 
+    // Registered at BOTH paths, and they differ in one way worth knowing:
+    // pre-routing authenticates everything under /api/, so /api/v1/version
+    // needs a key (any key, scoped included) while /version at the root needs
+    // none. Both are offered because a client looks under /api/v1 - a consumer
+    // tried /api/v1/version, /api/v1/health and /api/v1/info and got 404 from
+    // all three - while a monitor outside the API wants no credential.
+    //
+    // It exists because a consumer that cannot ask which server it is talking
+    // to has to PROBE for a behaviour change instead: one of them discovered a
+    // 0.3.0 -> 0.5.1 jump only by inserting a duplicate row to see which error
+    // contract came back. A version string is not a secret, and the error
+    // shapes and /openapi.json already say more than this does.
+    auto version = [](const httplib::Request&, httplib::Response& res) {
+        sendJson(res, 200, {{"name", "smartbotic-vectorapi"},
+                            {"version", svapi::VERSION},
+                            {"commit", svapi::GIT_COMMIT},
+                            {"db_client", smartbotic::database::clientLibraryVersion()}});
+    };
+    svr.Get("/version", version);
+    svr.Get("/api/v1/version", version);
+
     svr.Get("/openapi.json", [share](const httplib::Request&, httplib::Response& res) {
         if (share.empty()) { sendJson(res, 404, {{"error", "not configured"}}); return; }
         std::ifstream f(share + "/openapi.json");

+ 11 - 3
src/handlers/vectors.cpp

@@ -115,12 +115,20 @@ void registerVectorRoutes(ApiServer& s) {
         auto filters = parseSearchFilters(body);
         const std::string coll = qualify(project, name);
 
-        const std::vector<smartbotic::database::Client::SimilarityResult> results =
+        const VectorSearchResult found =
             vectorSearch(d->db.client(), coll, q, topK, minScore, filters);
 
         nlohmann::json arr = nlohmann::json::array();
-        for (const auto& r : results) arr.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
-        sendJson(res, 200, {{"results", arr}});
+        for (const auto& r : found.hits)
+            arr.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
+        // `results` keeps its shape and meaning; the two new keys are additive.
+        // `scan_capped` is the one that matters: without it a short answer and
+        // a complete one are indistinguishable, and a caller sweeping a
+        // filtered set cannot tell it has been given less than matches.
+        nlohmann::json out = {{"results", arr}, {"scan_capped", found.scanCapped}};
+        if (found.scanned > 0) out["scanned"] = found.scanned;
+        if (found.scanCapped) out["scan_cap"] = kVectorFilterScanCap;
+        sendJson(res, 200, out);
     });
 }
 }

+ 20 - 6
src/vector_search.cpp

@@ -4,11 +4,15 @@
 
 namespace svapi {
 
-std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
+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) {
-    if (filters.empty()) return client.similaritySearch(coll, query, topK, minScore);
+    VectorSearchResult out;
+    if (filters.empty()) {
+        out.hits = client.similaritySearch(coll, query, topK, minScore);
+        return out;   // no ranking walk, so nothing to cap
+    }
 
     smartbotic::database::Client::QueryOptions opts;
     opts.filters = filters;
@@ -21,7 +25,7 @@ std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
         if (!id.empty()) allowed.insert(id);
     }
     std::vector<smartbotic::database::Client::SimilarityResult> results;
-    if (allowed.empty()) return results;
+    if (allowed.empty()) return out;   // nothing matched the filter: complete
 
     // Walk the ranking from the top, widening until topK matches are found or
     // the ranking is exhausted. Because the scan is in descending score order,
@@ -37,12 +41,22 @@ std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
             results.push_back(r);
             if (results.size() >= topK) break;
         }
+        out.scanned = scan;
         if (results.size() >= topK) break;            // enough matches
-        if (page.size() < scan) break;                // ranking exhausted
-        if (scan >= kVectorFilterScanCap) break;      // bounded work
+        if (page.size() < scan) break;                // ranking exhausted: complete
+        if (scan >= kVectorFilterScanCap) {
+            // 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
+            // rows than asked for exits through "ranking exhausted" above and
+            // is correctly reported as complete.
+            out.scanCapped = true;
+            break;
+        }
         scan = std::min(scan * 4, kVectorFilterScanCap);
     }
-    return results;
+    out.hits = std::move(results);
+    return out;
 }
 
 } // namespace svapi

+ 24 - 1
src/vector_search.hpp

@@ -25,7 +25,30 @@ constexpr uint32_t kVectorFilterScanCap = 10000;
 /// stored vectors, so scoring still comes from similaritySearch and the two
 /// results are intersected - which means scores are identical to those of an
 /// unfiltered query.
-std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
+/// A search's hits plus whether the answer is COMPLETE.
+///
+/// The flag exists because a short answer and a complete one were previously
+/// indistinguishable. A filtered search walks the ranking only as deep as
+/// `kVectorFilterScanCap`, so once a collection holds more rows than that, a
+/// filter whose matches lie deeper in the ranking returns fewer hits than
+/// actually match - silently. Measured by a consumer on a 12448-row
+/// collection: a filter with 553 true matches returned 455 of the 500 asked
+/// for, which is almost exactly 553 x 10000/12448, with nothing in the
+/// response to say so. Harmless at the top_k of 5-10 most callers use; a wrong
+/// answer for anything sweeping a filtered set, and it worsens as rows grow.
+struct VectorSearchResult {
+    std::vector<smartbotic::database::Client::SimilarityResult> hits;
+    /// How deep into the ranking the last pass went. 0 for an unfiltered
+    /// search, which does not walk the ranking at all.
+    uint32_t scanned = 0;
+    /// True when the walk stopped at the cap while STILL short of `topK` and
+    /// the ranking was not exhausted - i.e. more matches may exist below.
+    /// False whenever the answer is known to be complete, which includes the
+    /// ordinary case of a filter that simply matches fewer rows than asked.
+    bool scanCapped = false;
+};
+
+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);

+ 164 - 0
tests/test_api_integration.cpp

@@ -2379,6 +2379,170 @@ TEST_F(ApiFixture, ARecycledCollectionNameInheritsNoConstraint) {
                                         "be refused; body: " << declared->body;
 }
 
+// --- novitax findings ------------------------------------------------------
+
+// A whole-document replace on a vector collection destroyed the stored
+// embedding SILENTLY - the call succeeded and the document stopped being
+// searchable - and the caller could not prevent it, because reads never return
+// the vector so a read-modify-write cannot put it back. Measured against the
+// database before fixing: a merge PATCH preserves the vector, an update drops
+// it. On data that cost money to produce.
+TEST_F(ApiFixture, ReplacingADocumentInAVectorCollectionIsRefused) {
+    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","vguard"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(), ct)->status, 201);
+    auto stored = c.Post((base + "/vguard/vectors").c_str(),
+                         nlohmann::json{{"vector",{1.0,0.0,0.0,0.5}},
+                                        {"metadata",{{"tag","a"}}}}.dump(), ct);
+    ASSERT_TRUE(stored); ASSERT_EQ(stored->status, 201) << stored->body;
+    const std::string id = nlohmann::json::parse(stored->body).value("id", "");
+    ASSERT_FALSE(id.empty());
+
+    auto searchable = [&]() {
+        auto r = c.Post((base + "/vguard/search").c_str(),
+                        nlohmann::json{{"query_vector",{1.0,0.0,0.0,0.5}},{"top_k",5}}.dump(), ct);
+        if (!r || r->status != 200) return std::size_t{0};
+        return nlohmann::json::parse(r->body)["results"].size();
+    };
+    ASSERT_EQ(searchable(), 1u) << "the vector should be searchable before we touch it";
+
+    // The replace is refused, by name, and nothing is written.
+    auto put = c.Put((base + "/vguard/documents/" + id).c_str(),
+                     nlohmann::json{{"tag","b"}}.dump(), ct);
+    ASSERT_TRUE(put);
+    EXPECT_EQ(put->status, 422) << put->body;
+    EXPECT_NE(put->body.find("vector_replace_unsafe"), std::string::npos) << put->body;
+    EXPECT_EQ(searchable(), 1u) << "the refused replace must not have touched the vector";
+
+    // PATCH is the documented way out, and it keeps the vector - the behaviour
+    // the guard points the caller at, so it has to be true.
+    auto patched = c.Patch((base + "/vguard/documents/" + id).c_str(),
+                           nlohmann::json{{"tag","c"}}.dump(), ct);
+    ASSERT_TRUE(patched); EXPECT_EQ(patched->status, 200) << patched->body;
+    EXPECT_EQ(searchable(), 1u) << "PATCH must not drop the embedding";
+
+    // And a PUT that DOES carry a vector is allowed: the caller has supplied
+    // what would otherwise be lost.
+    auto withVec = c.Put((base + "/vguard/documents/" + id).c_str(),
+                         nlohmann::json{{"tag","d"},{"vector",{0.0,1.0,0.0,0.0}}}.dump(), ct);
+    ASSERT_TRUE(withVec);
+    EXPECT_NE(withVec->status, 422) << "a replace carrying a vector must not be refused: "
+                                    << withVec->body;
+}
+
+
+TEST_F(ApiFixture, AVersionEndpointExistsAndIsReachableWithoutAKey) {
+    // A consumer discovered a 0.3.0 -> 0.5.1 jump only by probing a duplicate
+    // insert to see which error contract came back, because /api/v1/version,
+    // /api/v1/health and /api/v1/info were all 404.
+    httplib::Client anon("127.0.0.1", port_);
+    auto root = anon.Get("/version");
+    ASSERT_TRUE(root); ASSERT_EQ(root->status, 200) << root->body;
+    const auto j = nlohmann::json::parse(root->body);
+    EXPECT_EQ(j["name"], "smartbotic-vectorapi");
+    EXPECT_FALSE(j["version"].get<std::string>().empty());
+    EXPECT_TRUE(j.contains("commit"));
+    EXPECT_TRUE(j.contains("db_client"));
+
+    // Under /api/v1 too, because that is where a client looks - but that
+    // prefix is authenticated wholesale, so it needs a key.
+    EXPECT_EQ(anon.Get("/api/v1/version")->status, 401);
+    auto withKey = admin().Get("/api/v1/version");
+    ASSERT_TRUE(withKey); EXPECT_EQ(withKey->status, 200) << withKey->body;
+    EXPECT_EQ(nlohmann::json::parse(withKey->body)["version"], j["version"]);
+}
+
+TEST_F(ApiFixture, AScopedKeyMayListCollectionsButNotCreateThem) {
+    // Enumerating is not managing. A scoped key could read every document in a
+    // collection but not learn the collection existed, which forced a consumer
+    // to hardcode collection names into a backup script - so a collection
+    // added later was silently missed.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","listable"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+
+    auto mk = c.Post("/api/v1/keys",
+        nlohmann::json{{"label","lister"},{"projects",{project_}},{"admin",false},
+                       {"scope",{{"rules",{{{"collection","listable"},{"ops",{"read"}}}}}}}}
+            .dump(), "application/json");
+    ASSERT_TRUE(mk); ASSERT_EQ(mk->status, 201) << mk->body;
+    const std::string scoped = nlohmann::json::parse(mk->body)["key"];
+
+    auto listed = request("GET", base, "", "", scoped);
+    ASSERT_TRUE(listed);
+    ASSERT_EQ(listed->status, 200) << "a scoped key must be able to enumerate: " << listed->body;
+    // Bound to a named variable first: a range-for over
+    // nlohmann::json::parse(...)[...] iterates a destroyed temporary. The
+    // project's own conventions warn about this and I still wrote it.
+    const nlohmann::json listedJson = nlohmann::json::parse(listed->body);
+    bool saw = false;
+    for (const auto& m : listedJson["collections"])
+        if (m["name"] == "listable") saw = true;
+    EXPECT_TRUE(saw) << listed->body;
+
+    // And reading ONE collection's metadata, which used to be refused while
+    // the listing was allowed - so a scoped key could see a name and learn
+    // nothing about it.
+    auto one = request("GET", base + "/listable", "", "", scoped);
+    ASSERT_TRUE(one);
+    EXPECT_EQ(one->status, 200) << "a scoped key that can enumerate must be able to read one: "
+                                << one->body;
+
+    // Managing stays behind a full key.
+    auto created = request("POST", base,
+                           nlohmann::json{{"name","nope"},{"kind","json"}}.dump(),
+                           "application/json", scoped);
+    ASSERT_TRUE(created);
+    EXPECT_EQ(created->status, 403) << created->body;
+    auto dropped = request("DELETE", base + "/listable", "", "", scoped);
+    ASSERT_TRUE(dropped);
+    EXPECT_EQ(dropped->status, 403) << dropped->body;
+}
+
+TEST_F(ApiFixture, SearchReportsWhetherTheAnswerIsComplete) {
+    // A short answer and a complete one used to be indistinguishable. These
+    // collections are far below the scan cap, so every answer here is
+    // complete - the point is that the response SAYS so, which is what a
+    // caller sweeping a filtered set needs.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vsearch"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(),
+                     "application/json")->status, 201);
+    const std::string vecs = base + "/vsearch/vectors";
+    for (int i = 0; i < 5; ++i)
+        ASSERT_EQ(c.Post(vecs.c_str(),
+                         nlohmann::json{{"vector",{1.0, 0.0, 0.0, 0.0}},
+                                        {"metadata",{{"lang", i % 2 ? "hu" : "en"}}}}.dump(),
+                         "application/json")->status, 201);
+
+    auto unfiltered = c.Post((base + "/vsearch/search").c_str(),
+                             nlohmann::json{{"query_vector",{1.0,0.0,0.0,0.0}},
+                                            {"top_k",10}}.dump(), "application/json");
+    ASSERT_TRUE(unfiltered); ASSERT_EQ(unfiltered->status, 200) << unfiltered->body;
+    auto u = nlohmann::json::parse(unfiltered->body);
+    ASSERT_TRUE(u.contains("scan_capped")) << u.dump();
+    EXPECT_FALSE(u["scan_capped"].get<bool>());
+
+    auto filtered = c.Post((base + "/vsearch/search").c_str(),
+                           nlohmann::json{{"query_vector",{1.0,0.0,0.0,0.0}},
+                                          {"top_k",10},
+                                          {"filters",{"lang:eq:hu"}}}.dump(), "application/json");
+    ASSERT_TRUE(filtered); ASSERT_EQ(filtered->status, 200) << filtered->body;
+    auto f = nlohmann::json::parse(filtered->body);
+    ASSERT_TRUE(f.contains("scan_capped")) << f.dump();
+    // A filter matching fewer rows than top_k is COMPLETE, not capped - the
+    // flag must not cry wolf on the ordinary case.
+    EXPECT_FALSE(f["scan_capped"].get<bool>())
+        << "a filter with fewer matches than top_k is a complete answer: " << f.dump();
+    EXPECT_EQ(f["results"].size(), 2u);
+}
+
 // --- Project files ---------------------------------------------------------
 //
 // The store is name-addressed per project, and PROJECT ISOLATION IS OURS: the

+ 49 - 0
tests/test_registry.cpp

@@ -1,4 +1,5 @@
 #include "db_test_util.hpp"
+#include "errors.hpp"
 #include "collection_registry.hpp"
 using namespace svapi;
 
@@ -50,3 +51,51 @@ TEST(CollectionRegistry, BootstrapWarmsAllProjects) {
 
     db->dropProject(pa); db->dropProject(pb);
 }
+
+// A transient database failure must not be reported as "no such collection".
+//
+// Client::get returns nullopt for BOTH "no such document" and a transport
+// failure (it only throws for PERMISSION_DENIED), so the registry cannot tell
+// them apart from the return value alone. Left unhandled that reaches a caller
+// as 404, which a careful client cannot retry - adding 404 to a retry set
+// would retry every genuine absence - so a consumer lost a 6-minute ingest of
+// an 8 GB mailbox to a blip on a collection that existed before and after.
+//
+// Driven against an UNREACHABLE gateway, which is the sustained form of the
+// same ambiguity: every get() returns nullopt because nothing answers.
+TEST(RegistryTransient, AnUnreachableDatabaseIs503NotAMissingCollection) {
+    // Port 1 on loopback: nothing listens, so every call fails.
+    svapi::DbGateway dead("127.0.0.1:1", 100);
+    // connect() FIRST, and its failure is expected and ignored. The client
+    // crashes rather than throwing on an RPC issued before connect() has built
+    // its stub, so a test that skipped this would segfault and say nothing
+    // about the registry. Production always connects (main() exits 1 if the
+    // database is unreachable at startup), so connecting here is also the
+    // faithful shape - what is being tested is a database that goes away
+    // AFTER a successful start.
+    (void)dead.connect();
+    svapi::CollectionRegistry registry(dead);
+
+    try {
+        (void)registry.get("someproject", "somecollection");
+        FAIL() << "an unreachable database reported a definite answer about existence";
+    } catch (const svapi::ApiError& e) {
+        EXPECT_EQ(svapi::httpStatus(e.code), 503)
+            << "must be retryable, not a 404 the caller can never retry";
+        EXPECT_EQ(e.slug, "db_error");
+    }
+}
+
+// The other half: against a REACHABLE database, a genuinely absent collection
+// must still be reported as absent rather than as an outage. The fix must not
+// turn every 404 into a 503.
+TEST(RegistryTransient, AGenuinelyAbsentCollectionIsStillAbsent) {
+    auto db = testutil::connectOrNull();
+    if (!db) GTEST_SKIP() << "smartbotic-database not reachable";
+    svapi::CollectionRegistry registry(*db);
+    const std::string project = testutil::tmpName("transient");
+    db->ensureProject(project);
+    registry.ensure(project);
+    EXPECT_FALSE(registry.get(project, "definitely-not-there").has_value());
+    db->dropProject(project);
+}