llms.txt 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. # smartbotic-vectorapi
  2. > General-purpose REST API over smartbotic-database. **Multi-project**: every
  3. > collection and document lives under a named project supplied as a URL path
  4. > segment (e.g. `/api/v1/projects/{project}/collections`). **Multi-key**: each
  5. > API key carries a list of project grants (MySQL-style; `["*"]` for all); admin
  6. > keys additionally manage projects and keys. Auth: `Authorization: Bearer <KEY>`.
  7. > Machine-readable spec: `/openapi.json` (OpenAPI 3.1).
  8. ## Hostnames: the short path form
  9. Every project-scoped route accepts TWO shapes:
  10. /api/v1/projects/<project>/collections/<c>/documents (always works)
  11. /api/v1/collections/<c>/documents (project from the Host header)
  12. The short form works ONLY on a hostname registered to a project. On the admin or
  13. global hostname a short path names no project and answers **404** - it does not
  14. fall back to a default.
  15. A project hostname serves `/api/*`, `/fn/*` and `/healthz` for ITS project only.
  16. Naming a different project in the path there answers **404**, not 403: a project
  17. hostname must not confirm that another project exists. The web UI and `/docs` are
  18. not served on a project hostname.
  19. HOST GATING IS OFF until the deployment names itself (`admin_hostname` or
  20. `global_hostnames` in global settings). Until then project hostnames are stored
  21. and inert, and `GET .../settings/hostnames` reports `served: false` so the two
  22. states are distinguishable. A request whose Host is a bare IP address or
  23. `localhost` is treated as the admin surface, so configuring a hostname is not a
  24. one-way door.
  25. - `GET /api/v1/projects/{p}/settings/hostnames` (admin) -> `{project, hostnames, served}`
  26. - `PUT /api/v1/projects/{p}/settings/hostnames` (admin) - body `{"hostnames":[{"host":"...","path_style":"short"|"full"}]}`
  27. `path_style` defaults to `"short"`. **The PUT REPLACES the whole list**, like the
  28. key-scope PATCH - a partial list silently drops the rest, and merging would make
  29. removing a hostname impossible. Read the current list, edit it, send it whole.
  30. Refusals are three distinct slugs because the remedies differ (all 422):
  31. `invalid_hostname` (change the value - a wildcard, port, scheme, path or
  32. single-label name is refused; a wildcard belongs in a certificate, not here),
  33. `hostname_taken` (another project holds it), `hostname_reserved` (it is the
  34. deployment's own admin or global name). Re-claiming a hostname your own project
  35. already holds is accepted, so saving an unchanged list is idempotent.
  36. ## Projects
  37. Requires a valid key. Admin-only operations are noted.
  38. - `GET /api/v1/projects` - List projects the key may access (admin sees all).
  39. - `POST /api/v1/projects` `{name}` - Create a project (admin).
  40. - `GET /api/v1/projects/{project}` - Get project info (collection/document counts).
  41. - `DELETE /api/v1/projects/{project}` - Drop a project (admin; the `default` project cannot be dropped).
  42. ## Keys (admin)
  43. All key-management endpoints require an admin key.
  44. - `GET /api/v1/keys` - List keys. Secret value is masked; returns `id`, `key_prefix`, `label`, `projects`, `admin`, `created_at`, and `scope` (if present). Use `id` to reference the key in PATCH/DELETE.
  45. - `POST /api/v1/keys` `{label, projects:[], admin?, scope?}` - Generate a new key. Returns the secret key value **once** (store it immediately) plus the stable `id`. Pass a `scope` object (see below) to create a capability-scoped key.
  46. - `PATCH /api/v1/keys/{id}` `{label?, projects?, admin?, scope?}` - Update grants for an existing key, identified by its `id` (not the secret). Pass `scope: null` to clear an existing scope.
  47. - `DELETE /api/v1/keys/{id}` - Revoke a key by `id`. Active sessions using it are immediately invalidated.
  48. ### Capability-scoped keys
  49. A non-admin key may carry a `scope` object that restricts what it can do. Scoped keys are designed to be safely embedded in untrusted clients (browser frontends, mobile apps, n8n workflows). A scoped key cannot manage collections or projects regardless of its project grants.
  50. `scope` fields:
  51. - `rules` (required, non-empty array) - Each rule specifies a `collection` name and the permitted `ops` array (`read`, `list`, `search`, `insert`, `update`, `delete`). A request succeeds only if a matching `{collection, op}` rule exists. A rule may also set `require_human_token: true` (see CAPTCHA below).
  52. - `origins` (array of strings, default empty) - Allowed `Origin` header values. When non-empty, requests without a matching `Origin` header are rejected with 403 (**fails closed** - no origin header means denied). Use this to pin a key to a specific domain.
  53. - `rate_limit_per_min` (integer, default 0 = unlimited) - Per-key request rate limit. When the limit is exceeded the server returns **429** with a `Retry-After: 60` header. Four properties worth knowing before you tune a client against it, because none of them is guessable:
  54. - **The bucket is per KEY, not per project and not per source IP.** Two callers share an allowance only if they present the same key. So a dashboard a person refreshes and a batch script are independent as long as they hold different keys - which is usually the cheapest fix for a client hitting this, since it needs no change on our side.
  55. - **The window is FIXED, not sliding** (the limiter buckets on the wall-clock minute). A burst spends the whole allowance at once and every later call in that same minute is refused, rather than the allowance draining smoothly. A burst straddling a minute boundary can therefore land up to twice the limit inside a rolling 60 seconds, and an evenly paced client gets far more useful throughput out of the same number than a bursty one.
  56. - **A refused request does NOT consume allowance.** Retrying a 429 does not dig the counter deeper, so your backoff does not need to be aggressive to protect the limit. What a retry does cost is concurrency, which is a separate and real cost - see the note on paced requests below.
  57. - **A request is charged once, not once per thing it touches.** A collections listing that examines fifty collections spends one token, not fifty; otherwise a single request could rate-limit you.
  58. **Pace requests rather than bursting them.** The server is modest and concurrency is the cost that is easy to miss: many simultaneous requests do not finish sooner, they all finish later, roughly in proportion to how many are in flight. If one page load fans out into tens of calls, the useful change is almost always to reduce the fan-out - cache an inventory you re-read every time, or ask for what you need in one call - rather than to retry harder.
  59. - `expires_at` (integer, default 0 = never) - Unix epoch seconds after which the key is treated as expired; auth returns 401.
  60. **The Origin allow-list now covers the collections LISTING too** (0.15.0+). It always covered document and vector operations; the listing authorized through the project grant plus the scope filter and never consulted the list, so a key with an allow-list could enumerate a project's collection names, document counts and sizes from ANY origin while being refused every document in them. That mattered because a browser-publishable key is, by definition, a key anyone can read. Now `GET /projects/{p}/collections` answers **403** `forbidden` for an origin outside the list, exactly as a document read does.
  61. - **A key with NO `origins` is unaffected** - an empty list means any origin, which is what a server-side key should use.
  62. - `ip_allow` on a KEY scope is **refused with 422 `unsupported_option`**, not stored. Nothing checks it for an API key, and a control that reads back from the server while never being applied is worse than one that is absent - an operator would believe a key was pinned to their office address. It is a **function policy** field only (see the policy route). For a browser key, `origins` is the control that works; a server-side key has none today, because a non-browser client sends no `Origin` header.
  63. - **An ABSENT `Origin` header is refused when a list IS set**, on the listing and on every other capability-checked route alike. This is long-standing behaviour rather than new, and it is why **a key intended for server-side use must not carry an allow-list at all**: a non-browser client sends no Origin, so it can never satisfy one. A test pins the two routes to the same answer so they cannot drift apart again.
  64. **A scope refusal names what it refused and what you hold** (0.15.0+). A 403 `forbidden` from a scoped key carries a message naming the collection and the operation asked, plus the collections the key IS granted, and `error.details` with `collection`, `operation` and `granted` (each `{collection, ops}`). **The status is 403 whether the collection is outside your scope OR does not exist, and that is deliberate** - answering 404 for an absent collection would let a scoped key discover which collections exist in its project outside its own scope. So the message says as much: only you can tell a misspelled name from one nobody provisioned, and the answer will not tell you. Before 0.15.0 the message was just "scope does not permit this operation", which named neither and sent people to re-verify their key rather than the string.
  65. ### CAPTCHA-gated operations
  66. A scope rule may set `require_human_token: true`. When this flag is active, the client must supply an `X-Captcha-Token` request header containing the CAPTCHA challenge response. The server verifies the token via the configured provider endpoint and returns **403** `captcha_required` if the token is absent, invalid, or if no provider is configured. Configure the provider via the settings API: `captcha_provider` (`"turnstile"` or `"hcaptcha"`), `captcha_secret` (server-side secret), and `captcha_verify_url` (full verify endpoint URL).
  67. Example scope (insert-only, origin-pinned, rate-limited, expiring):
  68. ```json
  69. {
  70. "rules": [{"collection": "designs", "ops": ["insert"]}],
  71. "origins": ["https://app.example.com"],
  72. "rate_limit_per_min": 60,
  73. "expires_at": 1893456000
  74. }
  75. ```
  76. ## Collections
  77. Project-scoped. A key must be granted the project.
  78. - `POST /api/v1/projects/{project}/collections` `{name, kind:"json"|"vector", vector_dimension?, embedding_model?}` - Create a collection. `vector_dimension` is required for `kind=vector`. `embedding_model` defaults to the server's `default_embedding_model` setting.
  79. - `GET /api/v1/projects/{project}/collections` - List collections with metadata (incl. `document_count`, `size_bytes`). Query params (all applied server-side): `q` (case-insensitive name substring filter), `sort` (`name`|`kind`|`documents`|`size`|`created_at`, default `name`), `desc` (bool).
  80. **This route is more expensive than it looks, so do not call it on every page load.** It reports a live `document_count` and `size_bytes` per collection, and it gathers those per collection rather than in one shot, so its cost grows with the number of collections in the project - measured at roughly 0.4 s for eleven collections against 2 ms for an ordinary document listing. The inventory changes rarely; read it once and keep it for the session.
  81. **BREAKING FOR SCOPED KEYS: this listing is now FILTERED BY YOUR KEY'S SCOPE.** A key with scope rules sees only the collections at least one of its rules mentions; previously a project grant alone was enough, so a key granted exactly one collection could read every collection's name, document count and size in that project. A full (unscoped) key is unaffected.
  82. The op asked is "does any rule mention this collection", deliberately weaker than a `list` grant: if your key may read one document there, the collection's existence is not a secret from it, so a `read`-only rule still shows the name. What you no longer get is an enumeration of collections your key cannot touch at all. A collection outside your scope is simply ABSENT - there is no 403 and nothing names what was withheld, the same way a disabled function is 404 on `/fn` rather than 403.
  83. **The response now carries `scope_filtered`** (always present): true for any scoped key, false for a full one. It means "this listing shows only what your scope permits" and NOT "something was hidden" - it is true even when nothing was withheld, so it leaks nothing a key holder cannot already derive from their own scope. Read it before concluding a project is empty: an empty `collections` with `scope_filtered: true` means your key reaches nothing here, which is a different fact from the project having no collections.
  84. - `GET /api/v1/projects/{project}/collections/{name}` - Get collection metadata.
  85. - `DELETE /api/v1/projects/{project}/collections/{name}` - Drop a collection and all its documents.
  86. Collection names may not start with `_` or the reserved prefix `vectorapi_`.
  87. ## JSON documents
  88. Arbitrary JSON CRUD under a `kind=json` collection.
  89. - `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.
  90. **A FILTER'S VALUE IS PARSED AS JSON, AND FALLS BACK TO A LITERAL STRING WHEN IT IS NOT VALID JSON. SO ALWAYS DOUBLE-QUOTE A VALUE YOU MEAN AS A STRING.** This is one rule and it explains every surprise below, all measured on a live collection:
  91. - `approved:eq:true` matches a stored boolean; **`approved:eq:True` and `approved:eq:1` match NOTHING.** `True` is not a JSON literal so it becomes the string `"True"`, and `1` becomes the number 1. Neither equals a boolean.
  92. - `year:eq:2026` matches a stored integer; **`year:eq:"2026"` matches nothing**, and vice versa. Comparison is typed, not coerced.
  93. - **`productVersion:eq:2026.1` matches NOTHING against the stored string `"2026.1"`**, because `2026.1` is valid JSON for the NUMBER 2026.1. `productVersion:eq:"2026.1"` matches. And `productVersion:eq:2026.1.3` matches the stored string `"2026.1.3"` - only because three dots is not valid JSON, so it falls back to a string.
  94. - **THE TRAP THAT FOLLOWS, and it is a real one: a version-like value is a NUMBER or a STRING depending on how many dots it happens to have.** A client written and tested against `2026.1.3` works, ships, and silently returns nothing the day the value becomes `2027.1`. Double-quote it and the problem does not exist.
  95. - `productVersion:eq:'2026.1'` matches nothing: JSON has no single-quoted strings, so the value is the literal six-plus characters `'2026.1'` INCLUDING the quote marks.
  96. - The operators are `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `contains`, `exists`, `regex`, `search`. **It is `ne`, not `neq`** - an unknown operator is refused 400 `bad_filter` naming it, which is deliberate: a mistyped operator must never be guessed at.
  97. **COMPARISONS ORDER ACROSS TYPES, SO A RANGE CAN MATCH A VALUE OF A DIFFERENT KIND - AND THIS CHANGES IN DATABASE 2.18.0.** It was never specified; it is being fixed. From 2.18.0 a range operator (`gt`/`gte`/`lt`/`lte`) matches only number-to-number or string-to-string, so a null, a boolean, an object, an array or a type mismatch never satisfies one on either side, and a null or boolean BOUND matches nothing (5 and 5.0 are both numbers, so they still compare). **`eq`/`ne` are NOT changing** - they keep JSON equality, so `eq null` still matches an explicit null and `ne 2024` still matches null, true and strings while still excluding an absent field. `exists` is unchanged. **2.18.0 is RELEASED.** It is a SERVER-side change, so it takes effect when the database is upgraded and the client version is irrelevant; pin `smartbotic-database (>= 2.18.0)` when you want it, and a client from 2.18.0 on can probe the capability name `typed_range_filters`. Note a PAIR of numeric bounds (`gte X` AND `lte Y`) already excluded nulls and absent rows before this change, on every version - a null sorts below every number, so it fails the `gte` half. Only a SINGLE `lt`/`lte` bound over-matched nulls and booleans, and a single `gt`/`gte` bound over-matched strings. Until then, the behaviour below is what you get. Values order by TYPE: `null` < boolean < number < string. An ABSENT field is different again: every range operator, and `ne`, return FALSE for it. Measured on 2.17.2 over rows holding null, absent, `2024`, `2030`, `"1900"` (a string) and `true`:
  98. ```
  99. year:lte:2025 -> null, true, 2024 <- null and a BOOLEAN pass a numeric upper bound
  100. year:lte:1900 -> null, true
  101. year:gte:2025 -> 2030, "1900" <- a STRING passes a numeric lower bound
  102. year:ne:2024 -> null, true, 2030, "1900" (absent is excluded)
  103. ```
  104. **Both directions over-match, and a filter used as a validity or visibility gate admits rows the author believed it excluded - the same failure direction as a dropped filter, answering 200.**
  105. **`field:exists:true` DOES NOT FIX IT**, and this correction matters: a field holding an explicit `null` EXISTS, so `exists` excludes only the absent case, which was never the problem. **A PAIR of bounds is the safer form** (`validFrom:lte:X` AND `validTo:gte:X`), because the `gte` half rejects the nulls the `lte` half admits. But note it does NOT save you from the string case: a string stored in a numeric field passes a `gte` bound too, since strings sort above every number. **The only robust guard against the wrong TYPE being stored at all is a collection schema** (database 2.16.0+), which is the real remedy for this class rather than a cleverer filter.
  106. Note also that SORT and FILTER disagree about an absent field: sort places it after everything ascending, while a filter never matches it. They agree on `null`, which sorts lowest.
  107. **A SLUG THIS SERVICE CAN RETURN IS NOT NECESSARILY A SLUG YOU CAN OBSERVE: the set is bounded by the DATABASE CLIENT this build links, not by the database's release notes.** Measured, and it caught us: `encrypted_field` **422** shipped in 0.12.0 and cannot fire on a deployment whose client predates 2.17.0, because carrying the server's error REASON on read calls (`find`, a filtered search) is a client-side change. Against a 2.17.1 SERVER with a 2.14.0 client the same refusal arrives as the generic `validation`, with the server's explanatory message intact. So a slug announced in a database release becomes observable only once this service is rebuilt against a client that forwards its reason - and `GET /api/v1/version` reports `db_client`, which is the library version and therefore the right field to read for this, while telling you nothing about the SERVER. **That pin HAS now moved: 0.13.0 links client 2.17.2, so `encrypted_field` fires for real** - a filter, sort or index on a field the database stores encrypted now answers 422 `encrypted_field` with `details.field`, where 0.12.0 on prod answered generic `validation`. The general rule stands for the NEXT slug: branch on `error.code`, treat an unexpected `validation` carrying a specific message as the same condition, and never match on message text to recover a slug you expected - add the handler and let it start firing when the pin moves.
  108. **`Retry-After` IS NOW KEYED ON THE CAUSE, AND ITS ABSENCE ON A 503 IS DELIBERATE RATHER THAN AN OMISSION.** Until 0.15.0 the only route that set it was a 429. Now `read_only` **503** carries `Retry-After: 30` and `db_unavailable` **503** carries `Retry-After: 5` - measured values rather than round numbers: a database that cannot be reached was observed recovering in 13-15 seconds a cycle during an outage, while a read-only lock is a recovery state rather than a blip and five seconds of hammering it helps nobody. A 429 keeps its `Retry-After: 60`, the limiter's own window.
  109. **But MOST 503s from this service still carry NO `Retry-After`, and that is the information.** A `db_error` 503 whose message is "insert failed" is a write that did not apply, and `no_runner` 503 needs an operator to configure a runner - no duration makes either of them succeed, so advising one would be inventing a remedy you would honour. So read the header as a POSITIVE signal ("this is transient, and here is roughly how long") and its absence as "retrying on a timer is not the fix here" - not as "the server forgot to tell me, so I will pick a number". The same rule applies to every status: a 4xx never carries it, because nothing but a changed request will help.
  110. **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), `message_too_large` **422** when a call is refused for size by the transport itself - it is **422 and not 429** because waiting cannot shrink a payload, and it is not named after your body because the limit applies in either direction: a stored document can grow past it through repeated PATCHes until it can no longer be read back, so you may have sent nothing large at all. The message carries both sizes and says which direction it was, `document_too_large` **422** when a write would make the STORED document bigger than a read could ever return - note a patch is judged on its MERGED result, so the body you sent may be small, `outcome_unknown` **504** when a WRITE timed out and may or may not have been applied (re-read before retrying; never blindly retry a non-idempotent write - this is deliberately NOT 503, which would mean "retry as-is"), and `memory_pressure` **429** when the database's admission control is refusing writes because IT is short of memory - the same remedy as a rate limit (wait, `Retry-After` is set) but deliberately a different slug, because `rate_limited` would have you throttle a client that was never the problem, `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**, `vector_missing` **422** (a document inserted into a vector collection without `_vector` - it would read back fine and never be findable by a search, so it is refused rather than stored. **`text` does NOT satisfy it: this route does not embed.** Only `POST .../vectors` embeds, so send text there. Note that is a statement about where TEXT goes, not about the only thing that route does: `POST .../vectors` takes `text` OR a pre-computed `vector` array, and with a `vector` it makes no provider call at all. A consumer planning a bulk migration read this line as "/vectors is the embedding route" and concluded every row of theirs would have to be embedded inside our process - so prefer it for explicit vectors too, since it checks the dimension against the collection's pin. The same refusal applies to `ctx.collections(...).insert()`, where `.store({text})` is the embedding path). **On the embedding path** (`POST .../vectors` carrying `text`, and `.store({text})` inside a function): `embedding_unreachable` **503** when the provider could not be reached or did not answer in time - the message names which PHASE ran out, connect or read, and how many ms elapsed, because the two are otherwise indistinguishable. And `embedding_failed`, where **the STATUS is the thing to branch on**, because one slug carries two failures with opposite remedies: **503 with a short `Retry-After`** when the provider itself answered 429 or 5xx, which is transient and worth retrying, and **422** when it answered any other 4xx (an unknown model, a rejected key) or returned a 200 whose body we could not parse, neither of which any amount of waiting fixes. The provider's own HTTP status is carried in the message and that is the ONLY place it is recorded - our access log keeps no error slug for a 4xx. **Before 0.18.2 both were 422**, so a transient provider blip told a caller to correct a request that was already correct: three of one consumer's 26,186 bulk writes were silently dropped rather than retried, because their retry set is keyed on status and 422 is not in it. The slug deliberately did NOT split, since it is a code consumers already branch on and the status carries the distinction. 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**.
  111. **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.
  112. **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`, `_expires_at`) 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. **`_expires_at` is reserved and stripped on writes, and is now RETURNED on reads and in the export.** It is the document's absolute expiry in epoch ms. Measured with a control: a row stored with `?ttl_seconds=3600` reads back carrying `_expires_at`, a row stored without one carries NO such field, and the export carries it on the first and not the second - so **absent means no expiry, never zero**, and you must test for the key's presence rather than for a zero value. Set an expiry with `?ttl_seconds=`, never by posting this field; posting it is silently stripped, which is deliberate - the database would otherwise store an invisible shadow copy that every read overwrites and no filter can reach.
  113. **A value may legitimately be in the PAST, and this is the part that bites a restore.** Expiry is swept lazily, so a row can outlive its deadline: a backup taken while the server was stopped keeps expired rows until a server opens the file again, and one was measured still physically present **121 hours** past its deadline. **So the restore rule has three branches, not two:** `_expires_at` absent means insert with no TTL; `_expires_at` in the PAST means **skip the row entirely**; otherwise set `?ttl_seconds=` to `ceil((_expires_at - now) / 1000)`.
  114. **Putting an expired row back makes it IMMORTAL, and every reassuring signal you would check stays green while it happens.** A restored row carries no TTL unless you give it one, so a 48-hour idempotency marker restored two days later suppresses forever the work it was meant to guard for two days. The diff is what hides it: every id back in place, every count matching, the verifier green. Report expired rows you left out (`1341 already present, 1 expired left out`) rather than silently, because the row that mattered is the one nothing would otherwise mention. And note the mirror of the same trap one layer up: **an at-most-once marker with a TTL guards a SCHEDULE and is never evidence of what happened** - if a person can re-run the job later, the record has to live somewhere permanent.
  115. **FILTERING on `_expires_at` (`lt`, `exists`) needs a database SERVER at 2.19.0 or newer**, unlike reading it, which needs only the client we ship. On an older server the field still comes back on reads and a filter naming it simply matches nothing useful. A row with no expiry is ABSENT for those filters rather than zero, so an upper bound cannot sweep up permanent rows.
  116. - `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.
  117. - `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 REFUSES `?ttl_seconds=` with 422 `unknown_option` rather than ignoring it** (previously it answered 201 and stored a PERMANENT row). The parameter cannot be honoured here at all - the database's update path takes no TTL - and honouring it on the create half of this upsert while dropping it on the replace half would be worse than either, since it would work only until the row existed. `details.unsupported` names it. **From 0.18.0 the refusal is answered BEFORE the collection is looked up, so it is 422 whether or not the collection exists.** Until then the same refused parameter answered 404 on a misspelled collection and 422 on a correct one, so a caller who got the name wrong never learned the parameter is unsupported - they fixed the name, retried, and only then met the 422. The order is authentication (401), authorization (403), the REQUEST (422), then the resource (404): a fault no amount of creating the collection would fix never hides behind the collection's absence. **To create a row with an expiry, POST with an `id`; to set or clear one on a row that already exists, PATCH with `?ttl_seconds=`.** This was a consumer's measured defect and is worth knowing why it mattered: a silent drop stored a permanent row where the caller had asked for a 1-hour one, their write returned 201, and the feature they were building existed precisely to stop a restore recreating an immortal at-most-once marker - so the drop produced exactly the bug the feature was written to prevent, and nothing but a read-back could see it.
  118. - `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".
  119. **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.
  120. - `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.
  121. - `GET /api/v1/projects/{project}/collections/{name}/export` - **Streaming backup, including stored vectors.** Answers **NDJSON** (`application/x-ndjson`): one JSON object per line, so the LINE is the unit of recovery and a truncated download loses the last row rather than the file. First line `{type:'header', collection, snapshot_at, vector_dimension, vector_dtype, rows_at_snapshot, batch_rows_cap, max_stream_seconds, include_vectors, vector_format}` (`snapshot_at` is server epoch seconds - "as of when" is the first question anyone asks of a backup, and a filesystem mtime does not survive a copy); then `{type:'row', id, document, vector_state, vector|vector_b64}` per document - **the vector field is named `vector` (a JSON array) with `vector_format=array`, and `vector_b64` (base64 of float32-little-endian) with `vector_format=base64`.** Handle BOTH names: a consumer who read only `vector` and exported as base64 saw a row reporting `vector_state: present` with no `vector` key, which looks exactly like the data loss `vector_state` exists to report; then `{type:'trailer', rows_sent, last_id, complete, content_sha256}`. **`content_sha256` is over each row's id and its RAW VECTOR BYTES, not over the emitted text**, so it is IDENTICAL whichever `vector_format` you asked for - you can export as base64, restore, re-export as an array and still compare digests. It is omitted rather than empty if it could not be computed. **`format` is NOT the parameter name and is now refused** - it used to be ignored, so `?format=base64` silently produced the ARRAY export, which for 12448 rows at dim 4096 is roughly three times the bytes and looks like it worked. The name is `vector_format`.
  122. **The exact construction, so you can recompute it rather than only echo it.** ONE rolling SHA-256 over every row in stream order, feeding exactly:
  123. `id` (UTF-8 bytes, not length-prefixed) || `0x1F` || the vector as float32 little-endian (ZERO bytes when the row has no vector) || `0x1E`
  124. The two separators are load-bearing: without them `"ab"+"c"` and `"a"+"bc"` would hash alike. It is NOT a hash per row combined afterwards, and it is NOT over the vector alone.
  125. **WHAT IT DOES NOT COVER, because a digest is routinely read as proving more than it does.** It covers the ids, the vector bytes and the ORDER. It covers NO OTHER DOCUMENT FIELD. A restore that reproduced every embedding perfectly while losing every other key in every document - every label, every tenant marker, every piece of text - matches this digest EXACTLY. So `content_sha256` reproducing is not "the restore is proven"; it is "the embeddings and their order are proven". The metadata needs its own witness, and you must know which copy of your data answers that question before you need it at 3am. A consumer found this in their own backup note, which had said the digest comparison was "the only thing that actually proves a restore" - true of the vectors, false of everything else in the row, and false in the direction that looks fine. Note the live retrieval check has the same blind spot: a row is its own nearest neighbour at score 1.0 whatever its other fields say, so the two checks people usually pair do not between them see a metadata loss.
  126. **Because it is ONE hash across the stream, it covers ORDER as well as content:** an export carrying every correct row in a different sequence does NOT match. Per-row digests combined afterwards would have accepted that, so this is a stronger guarantee than it first looks - and it is why the recipe above must be applied in stream order rather than to a sorted set of rows. **FEED THE ROWS IN FILE ORDER; DO NOT SORT THEM.** Sorting by id is an obvious tidy-up and it produces a mismatch indistinguishable from corruption - so if this check fails, confirm you have not reordered anything BEFORE concluding the data is bad. When a check fails the first question is whether the CHECK is wrong, not whether the data is. Verified against a 12447-row production export: the recipe above reproduces the trailer's value exactly. **`rows_sent == rows_at_snapshot` with `complete: true` is your checksum** - one uninterrupted call is an exact snapshot with no row skipped or repeated, in id order. Needs BOTH the `list` and `read` grants: `list` alone could already learn the ids and must not get the contents, and `read` alone must not get an enumeration.
  127. **Params:** `include_vectors` (default **true** for a vector collection, and refused **422** `not_vector` on a json one), `vector_format` (`array` default, or `base64` for float32-little-endian). **Both are BIT-EXACT** - tested over 200k float32 values including denormals and the extremes - so choose on size, not on fidelity. `array` is the default because it restores directly (`_vector` on a document write takes exactly that shape) but it is ~3.7x larger: nlohmann prints a float32 widened to double with shortest-round-trip for DOUBLE, giving 16 digits where float32 needs 9, so it is verbose for precisely the same reason it is exact. Measured on 12447 rows at dim 4096: array 963 MiB, base64 261 MiB. **DO NOT ASK FOR GZIP ON VECTOR DATA.** Responses are compressible and the export inherits it, but measured at level 6 an array export costs ~121 s of SERVER CPU to save ~68 s of download, which is a net loss and a real cost on a shared host; base64 of float data compresses only 1.35x. Send `Accept-Encoding: identity` for a vector export. Gzip the json collections happily - document JSON compresses ~3.9x), `after_id` (resume), `batch_rows` (clamped, never refused).
  128. **`vector_state` is `present`, `none`, `missing` or `unknown`,** and a row that is not `present` carries NO `vector` field at all rather than an empty one - so a restorer cannot mistake "we do not have it" for "it is empty". **`missing` means the row HAD a vector and the entry is gone** (real data loss) and `unknown` means the row predates the database's marker, so neither should be restored as a plain document: re-embed from the source text instead, or you will store a row that reads back fine and can never be found by a search.
  129. **To restore:** replay each row as `PUT .../documents/{id}` with `document` plus `_vector` set to `vector`. The restored row gets FRESH metadata (`_version` restarts at 1, `_created_at` is the restore time); the originals are still in the exported `document` if you need them as data.
  130. **Resuming is skip-possible, never duplicate.** `complete: false` means the stream ended early - the server's `max_stream_seconds` cap, or your client disconnecting - and `last_id` is the cursor: call again with `after_id=<last_id>`. A resume starts a NEW snapshot strictly after that id, so it never repeats a row but can miss one inserted during the gap with an id sorting before the cursor. For an airtight copy take one uninterrupted stream.
  131. **A failure mid-stream emits a final `{type:'error', code, message, rows_sent, complete:false}` line** instead of simply stopping, because a stream that stops looks identical to a complete one whose trailer was lost. Treat a stream with no `trailer` AND no `error` line as failed.
  132. **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.
  133. - `DELETE /api/v1/projects/{project}/collections/{name}/documents/{id}` - Delete a document. Returns **409** `relation_restricted` (with `error.details.impacts`) if a restrict relation has children referencing it; see delete-impact below to preview this first.
  134. - `GET /api/v1/projects/{project}/collections/{name}/documents` - Find documents. Returns `{documents, count, has_more, total}`. Every row carries the same `_id`/`_version` metadata a single GET returns, so a filtered listing is a usable starting point for a conditional write without a second request per row.
  135. **`count` is the PAGE size; `total` is the exact number of rows matching your filters.** Both `has_more` and `total` are new in 0.18.2 and are emitted unconditionally, so an absent field means an older server and never "nothing to report". `total` is computed by the database before pagination and is exact rather than an estimate - it is not capped by `limit`, and it answers a multi-field filter, which nothing else here can: `indexes/{field}/values` counts ONE field over the whole collection. Before 0.18.2 the only way to get this number was to page the entire matching set, and one consumer measured that as a full scan plus 1750 documents of encoding to obtain a single integer, which is why their review portal shipped without a result count.
  136. **`limit` DOES NOT BOUND THE SERVER'S WORK, and the natural assumption is the opposite.** The database builds the whole match set, sorts it, and only then applies `offset`/`limit`, so `limit=20` and `limit=1000` scan identically. What `limit` saves is materialising and encoding the rows you did not ask for - which is real and is usually the whole cost (one consumer's queue screen went from 2.9 s to 453 ms by stopping at a page), but it means a narrow filter does not make a read cheaper and a small page is not a cheap query. Measured 2026-11-20 against a 13,093-row collection: the same predicate at `limit=1` and at `limit=1000` costs the same server-side.
  137. **Omitting `limit` gives you 100 rows, not every row.** A sweep written without one stops at 100 and returns a clean short page, which is indistinguishable from a set that really holds 100 rows - so pass `limit` explicitly, and use `has_more` rather than a short page to decide whether to continue.
  138. **A filter is index-accelerated only when it is genuinely selective, and "selective" means under ~10% of the collection.** Declaring an index does not make a filter on it cheap. The database picks, per VALUE rather than per field, the most selective indexed equality whose match count is under `rows/10`, and otherwise scans - because reading an index candidate costs a full document decode where a scan costs one parse, measured upstream at a ratio of ~8.6x, so a broad index plan is slower than scanning. It can also intersect two equalities, but only if the INTERSECTION clears the same bar. Worked example from prod: on 13,093 rows, `channel:eq:audio` matches 6,836 (52%) and `departmentKey:eq:ber` matches 3,520 (27%), so each is declined alone; together they match 1,750 (13.4%), which misses the 1,309-row threshold and is declined too, after paying to read and intersect 10,356 index entries. Filter ORDER is irrelevant - the planner measures each candidate's exact size first and takes the smallest - so there is nothing to tune by reordering. A field with few distinct values (a status, a boolean, a channel) will essentially never be index-served on its common values, only on its rare ones.
  139. **`sort` sorts the entire match set, not your page.** Sorting a filter that matches 13,000 rows to show 20 of them is a 13,000-element sort on every request.
  140. - `GET /api/v1/projects/{project}/collections/{name}/documents/{id}/delete-impact` - Preview what deleting this document would affect, without deleting it: `{would_be_blocked, impacts:[{relation, child_collection, child_field, on_delete, child_count, sample_child_ids, blocks}]}`. Read-only; follows the collection's read grant (a scoped key with a read rule may call it).
  141. **Filter grammar**: `field:op:value`, repeatable and ANDed. On documents it is the `?filter=` query param; on vector search it is the `filters` body array. The same grammar, operators and semantics apply to both, because the database evaluates them.
  142. Supported ops: `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `contains`, `exists`, `regex`, `search`.
  143. - `in` - value is a JSON array, e.g. `colour:in:["red","yellow"]`.
  144. - `contains` - **array membership**, not substring: it matches when the field is an array holding the value. `colour:contains:yellow` does NOT match the string `"yellow"`.
  145. - `search` - **IGNORES THE FIELD NAME.** A case-insensitive substring over the WHOLE document: its id, its keys, and every string and number in it. So `colour:search:ell` matches `"yellow"` in `colour` AND a document whose `note` says "excellent", AND one whose id contains `ell`. The field is syntactically required and semantically discarded - `nosuchfield:search:ell` matches exactly what `colour:search:ell` does. **For a substring within ONE field, use `regex` on that field.** Worth care if a `search` filter is doing scoping work: it admits rows you may believe it excludes, and in the same direction as a filter that was dropped entirely.
  146. - `regex` - regular-expression match, and the field IS honoured. This is the field-scoped substring: `colour:regex:ell`. **Three things about it are measurable and none of them announce themselves, so read this before building a search box on it.** **Which behaviour you get depends on the DATABASE version, and the two are very different.** **From database 2.20.0 the engine is RE2**: linear time, UTF-8 aware, and an invalid pattern is a real error (our 422 `invalid_pattern`, where the reason reaches you only through a 2.17.0-or-newer client - until then it arrives as the bare `validation` slug). `(?i)` works, non-ASCII included, and a character class is character-oriented, so `sz[áÁ]mfejt` matches `számfejt` and `[öÖ]` matches only text actually containing `ö` or `Ö`. **The one thing RE2 takes away: backreferences and lookaround are refused as `invalid_pattern`**, since RE2 has neither - that is the only direction in which a working query stops working. **Below 2.20.0** - which includes the currently deployed server, so this is what you will observe today - the four bullets below apply instead; they were measured against **2.17.2**. A server reports `re2_regex_filters` in its capabilities exactly when it has the new engine, so that, not a version string, is the thing to branch on if you must. **The advice that is correct under BOTH engines is to spell alternatives out as alternation** (`sz(?:á|Á)mfejt`) and to escape anything a user typed; a pattern written that way needs no change when the server moves, and avoiding nested quantifiers costs nothing on RE2.
  147. - **Matching is CASE-SENSITIVE and there is no flag to ask otherwise.** `text:regex:dolgoz` and `text:regex:Dolgoz` are different queries. **`(?i)` does NOT work** - it is not valid in this grammar, and an invalid pattern behaves as described two bullets down, so `(?i)Dolgoz` reads as "no matches" rather than as an error. Case-fold caller-side: spell the alternatives out, e.g. `text:regex:(?:d|D)olgoz`.
  148. - **The engine is BYTE-oriented, not UTF-8 aware, so a CHARACTER CLASS over non-ASCII text is wrong in BOTH directions.** A character class matches one BYTE, and any non-ASCII character is several. So `sz[áÁ]mfejt` can never match `számfejt` - it reads as "no matches" - while `[öÖ]` matches almost every Hungarian sentence, because `ö` and `Ö` share the lead byte `0xC3` with `á é í ó ú ü ő ű` and the class degenerates into match-nearly-anything. One failure reads as an empty corpus and the other as a broken search; neither reports a fault. **Use ALTERNATION of the whole sequences instead of a class**: `sz(?:á|Á)mfejt` is correct and was measured correct. The same caution applies to `.`, `\w` and any quantifier applied to a non-ASCII character, since each addresses bytes rather than characters.
  149. - **AN INVALID PATTERN MATCHES NOTHING AND ANSWERS 200 - it is NOT an error.** `text:regex:dolgoz(` cannot compile, and the response is a clean empty result list, indistinguishable from a valid pattern that genuinely matched no rows. Note this is a different layer from the **400** `bad_filter` below, which catches a malformed `field:op:value` SPEC: a well-formed spec carrying a broken PATTERN is not currently refused anywhere. **So never pass end-user text through to `regex` unescaped** - every unbalanced `(`, `[` or trailing `\` a customer types in a search box will look to them like an empty knowledge base. Escape the input, or validate the pattern before sending it.
  150. - **Avoid nested quantifiers on caller-supplied input** (`(a+)+`, `(.*)*` and similar). The engine backtracks exponentially: measured in isolation, a 6-character pattern of that shape against a 26-byte subject took 11 seconds and did not finish within 25 at 28 bytes. A pattern you construct yourself is fine; one assembled from user input is a way to make your own queries time out.
  151. - `exists` - `field:exists:true` / `field:exists:false`.
  152. The value is parsed as JSON when it parses (numbers, booleans, arrays), otherwise it is taken as a string. Everything after the second `:` is the value, so a value may itself contain `:`. A malformed spec or unknown operator is rejected with **400** `bad_filter`.
  153. Example: `?filter=age:gte:30&filter=name:eq:Alice`.
  154. Additional query params: `limit` (default 20), `offset` (default 0), `sort` (field name), `desc` (bool).
  155. **EVERY LISTING ROUTE NOW REFUSES A PARAMETER IT CANNOT HONOUR (422 `unknown_option`), AND THE RULE IS DERIVABLE RATHER THAN A LIST OF NAMES.** If a route implements a parameter it accepts it; if it does not, it says so instead of answering 200 with the parameter ignored. So `limit`, `offset`, `sort` and `desc` are correct HERE, because this route implements all four - and the same names are refused on routes that do not. The error names what you sent, lists what the route accepts, and carries `details.unsupported` (the names) plus `details.instead` (a map to the right name on THIS route, when there is one).
  156. Two things worth knowing before you adapt:
  157. - **An INCIDENTAL parameter is still ignored, deliberately.** A cache-buster, a proxy's addition, `_=<timestamp>`, `utm_*` - none of those ask for behaviour, so refusing them would be a regression rather than a fix. What is refused is the set a caller plausibly sends EXPECTING AN EFFECT.
  158. - **The names refused on each route are mostly OUR OWN other routes' spellings**, because that is where the real confusion comes from: `/documents` takes `sort`+`desc=true`, the index-values route takes `order=desc`, `/collections` searches with `q` while `/documents` filters with `filter`, and the export takes `vector_format` where `format` is the obvious guess. Each route therefore refuses the sibling spellings and `details.instead` names the local one.
  159. Per route: `/documents` accepts `filter`, `limit`, `offset`, `sort`, `desc`. `/collections` accepts `q`, `sort`, `desc` and is **not paginated**. `/files` accepts `limit`, `offset` only (fixed newest-first order, no search). The export accepts `include_vectors`, `vector_format`, `after_id`, `batch_rows` and **cannot export a subset**. A function's `/logs` accepts `limit` only - there is **no** `status` filter, so a request for just the failures would otherwise have returned runs of every outcome. `/schema/suggest` accepts `sample_limit` only.
  160. ## Collection schema (needs database 2.16.0+)
  161. An OPTIONAL per-collection JSON Schema, validated on every write. All four routes answer **501** `server_unsupported` against an older database - not 503, because no amount of retrying upgrades a database, and not 422, because the request is valid and there is nothing in the body to fix. Read `has_schema` on the collection GET to know whether one is set; it is OMITTED there when the database is too old, so absent means "cannot be determined", never "no schema".
  162. - `GET /api/v1/projects/{project}/collections/{name}/schema` - The schema as stored: `{schema, mode, audit_violations, refusals, armed}`. Needs only the **read** grant, deliberately: a schema is the contract you must satisfy to write, so anyone who may read the collection may see what shape it expects. **404 `no_schema`** when none is set - its own slug, so you can tell it from `not_found` (no such collection) without parsing a sentence. **`armed: false` means the stored schema no longer compiles and NOTHING is being validated** - check it, because a schema that silently enforces nothing reads as protection.
  163. - `PUT /api/v1/projects/{project}/collections/{name}/schema` `{schema, mode?}` - Set or replace it (project-manage). Every EXISTING row is validated first. `mode` is `enforce` or `audit`; **an unknown key, or a misspelled mode, is 422 rather than silently defaulted.** Answers `{mode, mode_defaulted, rows_checked, violating_rows, examples}` - and note `violating_rows` is reported on SUCCESS too, because audit mode succeeds while rows violate, which is the entire point of audit and would be invisible if only failures carried counts.
  164. **`mode` DEFAULTS BY WHETHER THE COLLECTION HOLDS DATA**, and the asymmetry is deliberate: `enforce` on an EMPTY collection (it cannot fail, and a live contract is what you want) and `audit` on a POPULATED one (enforce usually refuses on real data, and the counts are what you need first - defaulting to enforce there would make the common case look broken). `mode_defaulted` tells you which rule applied, so you never have to infer it.
  165. In `enforce` mode one non-conforming row refuses the whole change: **422 `schema_violation`** with `details.rows_checked`, `details.violating_rows` and up to ten `details.examples` of `{id, message, fields}`. A schema outside the supported subset is **422 `invalid_schema`** instead - a different slug on purpose, because one says fix your schema and the other says fix your data.
  166. - `DELETE /api/v1/projects/{project}/collections/{name}/schema` - Remove it; writes stop being validated. **Idempotent** - removing a schema that is not there reaches the requested end state, so it is 200, not 404.
  167. - `GET /api/v1/projects/{project}/collections/{name}/schema/suggest?sample_limit=N` - A schema generated FROM the data as a starting point (project-manage; it scans). Answers `{schema, rows_scanned, complete, applied}`. **`applied` is always `false`: this NEVER applies what it suggests.** Lengths and ranges are only described rather than enforced, so arming it unseen would create something that looks stricter than what it checks - edit it, then PUT it. **THE DESCRIBED-NOT-ENFORCED PARTS ARE THE DIAGNOSTIC HALF, not just a caveat - read `observed length` and `observed range` first.** A consumer ran `suggest` over 12447 live rows within an hour of this shipping and found a defect nothing else had surfaced: `validFrom` reported `observed length 10..24` while `validTo` reported `10..10`. **5847 of those rows - every chunk from one adapter - store a 24-character ISO timestamp where the other 6600 store a 10-character date.** The `type` was entirely clean (`['string','null']`), so a suggestion reporting types alone would have said everything was fine. It matters because range bounds on strings compare as STRINGS: `2026-12-31T11:57:17.000Z` sorts ABOVE `2026-12-31`, the date being a prefix of the timestamp, so a row valid on a 31 December is silently excluded from that year. They measured every year from 2017 to 2030 and found no live disagreement - the latest December timestamp was 2025-12-30, a margin of ONE DAY. **So the general form: a field whose TYPE is right and whose FORMAT is not will pass every type check you write, and the length range is what makes it visible.** **AND READ A SUGGESTION AS EVIDENCE ABOUT WHAT IS THERE, NEVER AS A PROPOSAL FOR WHAT SHOULD BE: it encodes whatever is already WRONG as if it were intended.** If a `year` field holds a stringified number anywhere in the collection, `suggest` faithfully proposes `"type": "string"` - so applying a suggestion unedited blesses the drift you were trying to find. That makes **audit mode the more informative of the two**: `suggest` tells you what the data looks like, while setting a schema you CHOSE in `audit` mode tells you what it would have rejected. The second is usually the question, and on a populated collection it is also the safe order - audit first, enforce once the counts come back clean. `complete: false` means it was built from a sample, so a field absent from the suggestion may still exist in the data; it is emitted unconditionally, so absence means only "older server".
  168. **A WRITE refused by the schema is 422 `schema_violation` on the DOCUMENT routes** - insert, update, upsert, patch (judged on the MERGED result, so a small body can trip it), increment, batch and restoreVersion. **`error.details.fields` is ALWAYS AN ARRAY, even for a single path, and `field` is never present on this slug** - unlike `duplicate_values`, which singularises. That is deliberate: several violating paths is the ordinary case here, so `details.fields.forEach(...)` has to work for one path too. The paths are dotted and indexed (`addr.zip`, `tags[2]`). The values are deliberately NOT echoed back, so nothing sensitive is reflected; the message names the rule and the size.
  169. **The schema does not cover `_vector`.** A vector collection's dimension stays its `vector_dimension`, and the vector is not part of the validated body.
  170. ## Indexes and facets
  171. Project-scoped, under a collection. Index create/drop require a full (non-scoped) key with project access - scoped keys cannot manage indexes.
  172. - `POST /api/v1/projects/{project}/collections/{name}/indexes` `{field, unique?}` - Declare an index on `field`, backfilling existing rows so it's usable immediately. Idempotent: re-declaring reports `already_existed: true`. With `unique: true`, refuses with **409** `duplicate_values` (`error.details.duplicate_examples`, up to five colliding document ids) if the field already holds duplicate values.
  173. - `POST /api/v1/projects/{project}/collections/{name}/indexes` `{fields:[...]}` - Declare a **composite unique constraint**: no two documents may hold the same COMBINATION of those fields, e.g. `{"fields":["chat_id","file_unique_id"]}`. Two or more fields, each named once; same `{rows_indexed, already_existed}` answer and the same **409** `duplicate_values` (with `duplicate_examples`) when existing rows already collide. A document in which ANY of the fields is absent or null does not participate (the SQL rule for a NULL in a unique key). It is always unique and backs no query, so `unique:false` is **422**. `field` and `fields` are two spellings of one request: sending **both** is **422** `ambiguous_body`, never resolved by precedence.
  174. - `GET /api/v1/projects/{project}/collections/{name}/indexes` - List indexes: `{indexes:[{field, distinct_values, entries, unique}], composite_unique:[{fields:[...], unique:true}]}`. `indexes` keeps exactly its old shape; composite constraints are reported under the separate `composite_unique` key because a composite has no `distinct_values`/`entries` and is named by a list rather than a field.
  175. - `DELETE /api/v1/projects/{project}/collections/{name}/indexes/{field}` - Drop a single-field index. Idempotent: dropping an index that is not there is **200**, the requested end state having been reached either way.
  176. - `DELETE /api/v1/projects/{project}/collections/{name}/indexes?fields=a&fields=b` - Drop a composite unique constraint, named by its **exact** field list (repeat `fields` once per field; order does not matter, and a missing or single-field list is **422**). Idempotent like the single-field drop, so a list naming no existing constraint is **200**, not 404. The list lives in a query param because it cannot live in the path: joining it would need a separator no field name may contain. Answers `{dropped_fields:[...]}`.
  177. - `GET /api/v1/projects/{project}/collections/{name}/indexes/{field}/values?limit=N&order=asc|desc` - Distinct values of an indexed field with their counts: `{values:[{value, count}], truncated, limit?}`. Index-dependent by design: an empty list for an unindexed field, and for array-valued fields whose index keys are elements rather than values. `limit` is **1..1000** (default 100).
  178. **THIS ROUTE IS NOT PAGINATED AND HAS NO TOTAL, and it now says so rather than pretending.** `offset`, `page`, `cursor`, `sort`, `fields`, `after` and `skip` are **refused 422 `unknown_option`** naming what you sent and what is accepted. Before that, `?offset=1000` answered **200 with the FIRST page** - the handler never read it and the client has no offset to honour - so a caller paginating looped forever believing it was progressing. An *incidental* query parameter (a cache-buster, a proxy's addition, `_=<timestamp>`) is still ignored rather than refused: refusing `offset` is the point, refusing `_=1760000000` would be a regression.
  179. **`truncated` is ALWAYS present, true or false** - so an absent `truncated` means exactly one thing, a server older than 0.13.0, and never "complete". When true, `limit` echoes the cap that bit. There is deliberately **no total**: nothing in the database counts distinct values (`count` counts rows), and a number we could not stand behind would be worse than none. If you need one, hold the data yourself. **A field with more distinct values than the cap therefore returns a PARTIAL facet whose counts sum to less than the collection** - which looks like a data problem on that one field, because only high-cardinality fields cross the cap. A consumer measured `sourceId` summing to 72% of a 12447-row collection and nearly filed it as corruption. So "an index is the only way to COUNT" holds only for fields whose cardinality you know is under 1000.
  180. ## Relations (admin)
  181. Relation names are per-project and **unqualified**: requests and responses always use the bare name; the internal `project:` prefix is never exposed. All relation endpoints require an admin key.
  182. - `POST /api/v1/projects/{project}/relations` `{name, child, child_field, parent, on_delete?, validate_on_write?}` - Create a relation: deleting a `parent` document affects `child` documents whose `child_field` references it. `on_delete` is one of `restrict` (default), `cascade`, `set_null`, `no_action`; anything else is 422.
  183. - `GET /api/v1/projects/{project}/relations` - List relations in the project.
  184. - `GET /api/v1/projects/{project}/relations/{name}` - Get a relation by name.
  185. - `DELETE /api/v1/projects/{project}/relations/{name}` - Drop a relation by name.
  186. - `GET /api/v1/projects/{project}/collections/{name}` also returns `relations_enforced` (bool). It is **absent** when the server could not determine it, which never means disabled.
  187. - `PUT /api/v1/projects/{project}/collections/{name}/relations-enforced` `{enforced}` - Enable/disable relation enforcement on a collection. **`relations_enforced` is read on the collection you are deleting FROM (the PARENT side of the relation), not on the child collection holding the reference.** Disabling it on the child has no effect on deletes issued against the parent; set it on the parent to let its deletes bypass restrict relations.
  188. ## RAG vectors
  189. Requires a `kind=vector` collection. Vectors are stored with cosine-similarity indexing.
  190. - **RESTORING AN EXPORT: the export writes base64 and the insert routes do NOT read it.** `GET .../export` with `vector_format=base64` emits each row's vector as **`vector_b64`**, but there is no base64 WRITE form - `POST .../documents` wants **`_vector`** as a JSON array of numbers, and `POST .../vectors` wants **`vector`** as a JSON array. So an export cannot be fed straight back in: expand the base64 to float32 little-endian numbers first. The 422 you get otherwise says `vector_missing`, which is accurate and unhelpful - it names what is absent rather than the perfectly good vector sitting in the field the exporter put it in. **A document inserted with a field called `vector` (rather than `_vector`) is now REFUSED** for the same reason: it used to be accepted with a 201 and then found by no search at all, because the body is stored verbatim while a search reads `_vector`. If you have rows already stored that way they are unfindable and need rewriting.
  191. - **Verifying a restore: a row count and an id set are structurally blind to the failure that matters.** They prove you stored something under the right names. A vector can survive byte-perfect in a file, be stored under the wrong field or in the wrong form, read back flawlessly and rank nowhere. The checks that catch it: every restored row should be **its own nearest neighbour at score 1.000000**, and the same `query_vector` should score a row **identically** in the restored and original collections. Only asking the store to retrieve by SIMILARITY exercises the thing a vector is for.
  192. - `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.
  193. - `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). **UPGRADE NOTE: a filtered search may now return MORE rows than it did before, and that is the fix rather than a break.** On the old capped path a filter whose matches lay deeper than the walk returned fewer hits than matched - one collection measured 426 rows for a filter with ~553 true matches at `top_k: 500`. On 2.14.0 the same query returns the full 500. So `top_k` now bounds a COMPLETE set rather than a truncated one, and code that was tuned around the smaller number - a page size, a display limit, a loop termination, a count treated as a ceiling - will see the larger one. If you built against the capped behaviour, check those before concluding a filter stopped filtering.
  194. **Against database 2.14.0 or newer a filtered search is a single server-side call: the filter selects candidates BEFORE ranking, so the answer is the exact top-K among matching rows, there is no scan cap, `scan_capped` is always `false` and `scanned` is `0`** - and it is FASTER than the same search unfiltered, because only matching rows are scored. Against an older server the service falls back to walking the ranking `scan_cap` deep, and there a filter whose matches lie deeper than the walk returns FEWER hits than match, which is what `scan_capped: true` reports. `scan_capped: false` always means the answer is complete; on 2.14.0+ it is complete by construction, on the fallback it means complete this time. **On the fallback, check it before treating a filtered result set as exhaustive.** Note `min_score` defaults to 0, which drops rows whose cosine is NEGATIVE - pass a negative `min_score` to see every match. Rows with equal scores are ordered by id, lowest first. The response also carries **`filter_mode`**: `"server"` means the database filtered before ranking, so there is no cap and **sweeping a filtered set is sound**; `"walk"` means the fallback emulation answered, so `scan_capped: false` means only "complete this time" and a sweep is NOT sound; `"none"` is an unfiltered search. Do not try to infer this from `/api/v1/version` - that reports the CLIENT library version while the path depends on the SERVER, so a newer client against an older server would read as the new path while running the capped one. **Inside a function `.search()` still returns an ARRAY**, and `scan_capped` and `filter_mode` ride on it as non-enumerable properties - `const r = await ctx.collections('c').search({...}); r.scan_capped; r.filter_mode;`. Indexing, `length`, iteration, spread and `JSON.stringify(r)` are all unchanged, so a script written before this behaves identically. The truncation warning still goes to the run's console as well, because that is what an author reading a log sees.
  195. 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.
  196. **Latency tip:** `query_text` triggers a synchronous server-side embedding call to the configured provider, which usually dominates request time (seconds for large models). Cosine search itself is sub-millisecond. If your client issues many searches (e.g. an LLM/n8n agent doing RAG), embed the query once on your side and pass `query_vector` to skip server-side embedding entirely.
  197. **Cache bypass:** Send `Cache-Control: no-store` on a `/vectors` or `/search` request to skip the server-side embedding cache - the text is re-embedded fresh and the result is not stored in the cache.
  198. ## Settings (admin)
  199. `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.
  200. All settings endpoints require an admin key.
  201. - `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.
  202. - `PUT /api/v1/settings` `{openai_api_base?, openai_api_key?, default_embedding_model?, cors_origins?, session_ttl_minutes?, webui_enabled?, default_project?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?, embedding_cache_size?, embedding_cache_ttl_sec?, embedding_cache_max_bytes?, embedding_cache_normalize?, embedding_client_pool_size?, captcha_provider?, captcha_secret?, captcha_verify_url?, client_ip_header?, client_ip_header_is_list?, trusted_proxy_cidrs?}` - Merge the supplied fields into the current settings and persist. Omit `openai_api_key` or `captcha_secret` (or pass an empty string) to keep the existing secret. Changes are hot-reloaded immediately; cache settings are applied instantly via `reconfigure()`.
  203. **Who the server thinks is calling** (`client_ip_header`, `client_ip_header_is_list`, `trusted_proxy_cidrs`). These decide the address a function policy's `ip_allow` is matched against, and the address written to the server's own access log. The rule that matters: a header is believed **only when the request arrived from an address in `trusted_proxy_cidrs`** - a header is text the client writes, so otherwise the caller would choose its own answer. Defaults are `X-Real-IP`, not-a-list, and loopback, which is what nginx in front of a loopback-bound vectorapi produces.
  204. - `client_ip_header: ""` reads no header at all and treats the peer address as the caller. That is the correct setting when nothing proxies the port.
  205. - `client_ip_header_is_list: true` for an `X-Forwarded-For` style header. The **last** element is used, not the first: nginx's `$proxy_add_x_forwarded_for` is "whatever the client sent, plus the real peer appended", so the first element is caller-controlled and only the last was vouched for by the proxy.
  206. - A `trusted_proxy_cidrs` entry that is not a CIDR range or bare address is refused with **422 `validation`** naming the entry, rather than dropped silently: a typo that disabled proxy trust would make every request appear to come from the proxy, which still looks like an address and so goes unnoticed.
  207. - **Getting these wrong refuses every caller of a function that uses `ip_allow`, not merely the wrong ones.** That is the deliberate fail-closed direction.
  208. ## Project embedding settings
  209. A project can point its embeddings at its own provider endpoint, key and model, which is how per-customer usage gets metered at the provider. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused.
  210. Precedence for one embedding call: the collection's own `embedding_model` wins, then the project override, then the global default. The endpoint and key are the project override when set, otherwise the global ones.
  211. - `GET /api/v1/projects/{project}/settings/embeddings` - Return `{effective, inherited, overrides}`. Each carries `openai_api_base`, `default_embedding_model`, `openai_api_key_set` (bool), `embedding_connect_timeout_sec` and `embedding_read_timeout_sec`. The API key itself is never returned. In `overrides`, an empty string means an inherited string field and `null` an inherited timeout.
  212. - `PUT /api/v1/projects/{project}/settings/embeddings` `{openai_api_base?, openai_api_key?, default_embedding_model?, embedding_connect_timeout_sec?, embedding_read_timeout_sec?}` - Omit a field to leave it unchanged; send `null` to clear the override and inherit the global value. The two timeouts are seconds and **narrowing only**: the effective value is `min(project, global)`, so a project can tighten but never lengthen how long it may hold a shared provider connection. A value above the global one is stored rather than refused, and becomes meaningful if an operator later lowers the global. An empty string is rejected with **422**. Setting `openai_api_base` without an `openai_api_key` for the same project is rejected with **422** `embedding_base_requires_key`, so the global credential is never sent to a foreign endpoint. A project key without a project base URL is allowed (own key, default endpoint).
  213. - `DELETE /api/v1/projects/{project}/settings/embeddings` - Drop every embedding override, timeouts included; the project inherits the global settings again. It does **not** touch the project's function policy or wall-time caps, which live in the same document but are admin-only.
  214. ## Project secrets
  215. The values a project's functions read as `ctx.env.<NAME>` - a bot token, a provider key, a webhook signing secret. Stored per project in the database, so filling `ctx.env` no longer needs shell access to the runner host.
  216. A secret value is **write-only**: no endpoint ever returns it, masked or otherwise. A `GET` reports the name, whether a value is set, and the timestamps.
  217. Writes are **admin-only**, like a function's policy: the value is a live credential every function in the project then runs with, and an overwrite cannot be undone by inspection. Listing and reading the metadata only needs a key granted the project (capability-scoped publishable keys are refused), because an author has to know which names their code may read.
  218. A `NAME` must match `[A-Z_][A-Z0-9_]*` and be at most 64 characters - the charset a POSIX environment variable can carry, so a stored secret and a host variable can never hold one name under two spellings. A value is at most 8192 bytes, and a project may hold at most 64 secrets.
  219. **Precedence:** a host variable `SVAPI_FN_<project>__<NAME>` in `runner.env` wins over a stored secret of the same name. The host file can only be written by someone on the runner host, so it stays the override that a stolen API credential cannot shadow - and nothing changes for a deployment that already keeps its secrets there.
  220. - `GET /api/v1/projects/{project}/secrets` - `{project, secrets:[{name, set, created_at, updated_at}], count, max_secrets, max_value_bytes}`. Names only.
  221. - `GET /api/v1/projects/{project}/secrets/{NAME}` - `{name, set, created_at, updated_at}`; **404** when the secret does not exist.
  222. - `PUT /api/v1/projects/{project}/secrets/{NAME}` `{value}` - **admin only**. **201** on a first write, **200** on a rotation; the response never carries the value. **422** for a bad name, an empty or oversized value, or `secret_limit` when the project is already at 64 secrets.
  223. - `DELETE /api/v1/projects/{project}/secrets/{NAME}` - **admin only**. **404** when there was no such secret.
  224. Deleting a project deletes its secrets, so a recycled project name inherits nothing.
  225. ### Per-project function limits
  226. - `GET|PUT /api/v1/projects/{project}/settings/functions` `{max_wall_time_ms}` (**admin only**) - The project's wall-time cap, now **per run kind**: `{"max_wall_time_ms": {"http": n|null, "job": n|null}}`. A bare integer is still accepted on PUT and sets BOTH kinds, and `null` clears both; an object sets only the keys it names. GET always returns the object form - a single number could not express "10 s for routes, 60 s for jobs", and leaving the old scalar in place would make a client that reads only it see `null` (no cap) while a cap was in force. Narrowing only: neither raises a ceiling.
  227. - `PUT /api/v1/projects/{project}/settings/functions` `{max_wall_time_ms: int|null}` **(admin)** - the ceiling a function here may ask for with its own `timeoutMs`. It can only NARROW: the effective budget is `min(descriptor timeoutMs or default, project max or kind ceiling, hard ceiling)`. Admin-only because it decides how long one project may hold a pooled runtime, and so how long it can delay every other project's interactive routes.
  228. **A job run and an HTTP run have different ceilings.** An HTTP route answers a caller holding a socket open (seconds); a queue-claimed run has nobody waiting (minutes, 120 s by default) and draws from its own pool lane, so a slow scheduled job cannot take the runtime an interactive route needs.
  229. ## Project files
  230. Small named binary assets per project, so everything customer-specific (a logo, an e-mail signature image) is tenant **data** rather than something bundled into a function's source - a project can then be cloned for another customer by changing data only. Reads follow the scope rules under the reserved pseudo-collection **`_files`**; writes and deletes need a full (non-scoped) key with project access, because replacing a tenant's asset is a management act.
  231. - `PUT /api/v1/projects/{project}/files/{name}` - Store the **raw request body** under `name`, taking the content type from the `Content-Type` header (default `application/octet-stream`). Not base64 and not a JSON wrapper: a file is bytes. **201** for a new name, **200** for a replacement, and a replacement makes the old bytes unreadable. Answers `{name, content_type, size, checksum, created_at}`. An empty body is **422**; over the size cap is **422** `file_too_large` (default **2 MiB**, `max_file_bytes` in the global settings).
  232. - `GET /api/v1/projects/{project}/files/{name}` - The bytes, with the stored content type, plus `X-File-Checksum` and a `Content-Disposition` naming the file. **404** when there is no such file.
  233. - `GET /api/v1/projects/{project}/files/{name}/info` - Metadata only, without moving the bytes.
  234. - `GET /api/v1/projects/{project}/files` - `{files:[{name, content_type, size, checksum, created_at}], has_more, total}`, newest first. `limit` (1-1000, default 100, clamped rather than refused) and `offset`.
  235. **`has_more` and `total` are ALWAYS present**, true or false, so an absent `has_more` means exactly one thing - a server older than this release - and never "that was everything". They come from the database and were previously discarded, which left a full page and the last page looking identical. `sort`, `order`, `q` and the rest are **refused 422**: the order is fixed and there is no search, so fetch a known file at `/files/{name}` instead. Note the newest-first order is applied WITHIN a page, so it is not a stable global ordering to page through.
  236. - `DELETE /api/v1/projects/{project}/files/{name}` - **404** when absent. Safe against content dedup: identical bytes stored under two names share storage and are reference-counted, so deleting one name leaves the other readable.
  237. - **A file name is an identifier, not a label.** Letters, digits, `.`, `-` and `_`, at most 128 characters, no leading `.`, no `..`, no path separator and no `:`. A bad name is **422** with the reason, never 404 - the name is unusable rather than missing, and a caller told "not found" would retry a name that can never work.
  238. - **Deleting a project deletes its files**, so a recycled project name does not inherit the previous tenant's assets.
  239. - In functions: `ctx.files.get(name)` -> `{name, content_type, size, checksum, created_at, base64}` or **null** when absent, `ctx.files.info(name)`, `ctx.files.list()`. Governed by the function policy under `_files`, exactly like a collection. **Read only** - a function cannot write or delete a file. A single `ctx.files.get()` is capped at **1 MiB** independently of the storage cap, because base64 inflates by a third and a run holds a pooled runtime with its own memory limit.
  240. ## Functions
  241. Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.
  242. ### Writing a function
  243. A function is an ES module exporting a trigger declaration and a default handler:
  244. ```js
  245. 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.
  246. export default async function (ctx) {
  247. const docs = await ctx.collections('kb_chunks')
  248. .filter(`topic:eq:${ctx.params.topic}`).limit(20).find();
  249. const hits = await ctx.collections('kb_chunks')
  250. .search({ query_text: ctx.query.q, top_k: 5, filters: ['lang:eq:hu'] });
  251. ctx.log('found', docs.length, 'documents');
  252. return { status: 200, body: { docs, hits } };
  253. }
  254. ```
  255. `on` fields: `id` (required), `type` (`http`, default), `route` (required for http), `method` (a string or an array of strings; **absent means every method**), `auth` (`public` default, or `key` to require an API key - http only, see "Calling a function"), `watch` (error only, see below), `timeoutMs` (clamped to the runner's ceiling), `singleFlight`. The STORED `descriptor` always reports `method` as an **array**, and omits it entirely when the function accepts any method - a client rendering it must not assume the singular form the source uses.
  256. `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
  257. **`type: 'error'` runs a function when ANOTHER function fails** (0.15.0+). Like `job` it declares no route and no schedule and **cannot be called directly** - there is no public endpoint, so nobody can fake an alert. `watch` names the function whose failures it answers and defaults to `*`, every function in the project.
  258. - It receives `ctx.body.failure` carrying `function_id`, `run_id`, `trigger`, `status`, `error`, `started_at` and `duration_ms`, plus `failure_kind` when the failure was classified (`function_fault`, `runner_fault`, `transient_lookup`, `malformed`). **`failure_kind` is ABSENT rather than empty when nobody classified it** - an HTTP run has no queue to classify it - so a handler can tell "not classified" from a classification it does not recognise. Everything is nested under `failure` so a handler can tell this payload from a cron or db one without guessing.
  259. - **The failing function's error text IS given to the handler**, unlike the caller of the failed function, who never sees it. A handler is server-side code written by the same tenant, which is the whole reason to have one.
  260. - **It is ENQUEUED, not run inline**, so it needs the job queue and the runner's `jobs.enabled`. A failing request never waits on the handler that reports it, and a slow handler cannot hold the socket of a request that already went wrong. Delivery is at-least-once like any job, **so a handler must be idempotent** - it may run twice for one failure.
  261. - **`watch` is matched EXACTLY; there is no globbing beyond the bare `*`.** A prefix match would quietly start catching functions added later, and a handler silently widening its own scope is the opposite of what you want from one.
  262. - **A FAILING ERROR HANDLER TRIGGERS NOTHING - not itself, and not another error handler.** This is a hard rule, not a depth limit: there is no legitimate reason to report the failure of a failure reporter, and the shape being prevented is a handler that tries to e-mail an alert, fails because egress is denied, and triggers itself forever on your own queue. Two handlers both watching `*` would otherwise ping-pong indefinitely. So **an error handler's own failures are visible only in the run log**, which is where to look when alerts stop arriving.
  263. - A disabled or invalid handler is not a handler, and with no job queue configured a failure dispatches nothing - deliberately silent, since a deployment with no queue has nothing to drain one either.
  264. - **A project can be denied the network entirely.** `PUT /api/v1/projects/{p}/settings/functions` with `{"network_egress":"deny"}` (admin only) stops **both** `ctx.fetch` and `ctx.mail` for that project, refused as `egress_blocked` **before any name is resolved** - so a denied project emits no DNS query either. `"allow"` restores it, `null` inherits. The GET returns the effective value plus `network_egress_set`, which says whether it was chosen for the project or inherited. The default is **allow**, for compatibility rather than preference: `ctx.fetch` shipped with no gate, so defaulting to deny would have stopped every already-deployed function that makes an outbound call. One setting covers both surfaces on purpose - gating one and not the other would let an operator believe a tenant was offline while the other stayed open.
  265. - **A BINARY request body arrives as base64, not in `ctx.body`.** When the bytes are not valid UTF-8 - an image, a PDF, a protobuf - `ctx.body` is **`null`**, `ctx.bodyBase64` carries the bytes and `ctx.bodyEncoding` is `"base64"`. They go under their own keys rather than into `ctx.body` on purpose: base64 in `ctx.body` would hand a function that knows nothing of binary a plausible-looking string that is not the body that was sent, and silent corruption is worse than an obvious `null`. `ctx.bodyEncoding` is **absent** for a text body, so a function written before this behaves exactly as it did. Note the bytes decide and the content type does not: a body declared `application/json` that cannot be a JSON string is still offered as base64.
  266. - `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.
  267. - **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}`.
  268. - 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.
  269. - **An UNKNOWN option on a vector `/search` body is now refused with 422 `unknown_option`, naming every unrecognised key.** It used to be accepted and ignored, which produced silently wrong answers rather than errors. Measured on prod before the fix: `topK: 3` (the camelCase misspelling) returned **five** rows, the default, so a caller asking for three got five and was told nothing; `minScore: 0.99` returned rows where the correct `min_score: 0.99` returns none; and **`filter:` in the singular returned the rows the caller meant to EXCLUDE**. The accepted set is `query_text`, `query_vector`, `top_k`, `min_score`, `filters`, `embedTimeoutMs`. Matching is exact and case-sensitive, so `Top_K` is refused rather than quietly accepted as a second spelling.
  270. - **`embedTimeoutMs` bounds the whole embedding call, connect phase included**, and is narrowing only - it cannot exceed what is left of the run's budget. It applies identically to `.search()` and `.store()`: both resolve their vector through the same code, so there is no asymmetry between them. Exceeding it is **504** `embedding_timeout`. A non-integer or non-positive value is **422**: it is validated rather than ignored, because an option that is accepted and does nothing is worse than one that is refused.
  271. - **Its RESOLUTION IS ONE SECOND, and the effective floor is 1 s per phase.** The HTTP client underneath takes whole seconds and treats 0 as "no timeout", so every value below 1000 ms resolves to the same thing: 1 s to connect plus 1 s to read. `embedTimeoutMs: 1` therefore allows up to **2 s**, not 1 ms, and a provider that answers inside that second succeeds normally - which reads exactly like the option being ignored. It is not: a value of 1 and a value of 999 are genuinely indistinguishable, and tuning inside that range does nothing. Ask for **2000 or more** if you want the split to be meaningful, and expect a timeout to surface at a whole-second boundary rather than at the millisecond you named. **From 0.18.1 the split favours the READ phase, and this changed because the old split was a defect.** Connect is capped at an absolute 2 s (operator setting `embedding_connect_cap_sec`) and still never takes more than half the available time, so a 6000 ms ask now becomes **2 s connect + 4 s read** where it previously became 3 s + 3 s. That mattered: a consumer whose voice agent asks for exactly 6000 ms was getting a THREE second read deadline, and the 504 then quoted 6000 ms - a number no phase ever had. A 4000 ms ask is unchanged at 2 s + 2 s, since half of four is already two. The two phases are SEQUENTIAL, so what the option bounds is their sum; it was never a promise that connect gets half. **The 504 message now names the deadline that was applied as well as the one you asked for**, so `embedTimeoutMs 6000ms was applied as connect 2s + read 4s` tells you where the time went without reading our source.
  272. - **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.
  273. - `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.
  274. - **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}`.
  275. - `ctx.mail` - **IMAP read and SMTP send.** Three calls, deliberately few, each opening one session and closing it. Connection fields are shared: `host`, `port` (optional, 0 or absent means the scheme default), `user`/`userSecret`, `password`/`passwordSecret`, `tls` (default **true**), `startTls`, `timeoutMs`. **Prefer `passwordSecret`/`userSecret`**: they name a project secret resolved host-side, so an error or a log that echoes your options object cannot leak it and an operator can rotate it without a code push. A literal `password` is accepted, because `ctx.env` already hands your script the value anyway. Naming a secret that does not exist is **422** `mail_secret_missing`, which names the secret and never a value; passing both a literal and a secret name for the same credential is `ambiguous_body`. An unknown option key is **refused, not ignored**.
  276. - `ctx.mail.read({mailbox, criteria, limit, ...})` -> `{messages: [...], matched: n}`. `mailbox` defaults to `INBOX`; `limit` defaults to 20 and is **capped at 200** (over it is refused, not clamped). `matched` is the size of the whole search result and `messages` the newest `limit` of it, so you can tell a full page from the end of the mailbox. Each message carries `uid`, `seq`, `flags`, `internal_date`, `size`, `header`, `text`, `body_sections` and a `headerEncoding`/`textEncoding` of `text` or `base64` - **mail is routinely not UTF-8**, so the encoding is stated rather than assumed. Reading uses `EXAMINE` and `BODY.PEEK`, so **it never marks mail as seen**.
  277. - **Each message carries DECODED convenience fields, so you do not have to parse the header at all**: `subject`, `from`, `from_address` (the bare address with the display name stripped), `to`, `cc`, `date` and `message_id`. They are unfolded and RFC 2047-decoded host-side by the same implementation the send path encodes with. A value that will not decode is passed through exactly as it arrived rather than raising, because a malformed header is the sender's doing and one bad subject must not make a mailbox unreadable. `date` is left as sent, since turning an RFC 5322 date into an instant is a separate decision with its own failure modes. Absent headers are empty strings, never missing keys.
  278. - **`header` is still returned RAW alongside those fields, and raw means FOLDED - do not parse it with an obvious regex.** Measured against a real provider: a long accented subject came back as `Subject:<CRLF> =?UTF-8?B?...?=<CRLF> =?UTF-8?B?...?=`, with **nothing on the `Subject:` line itself** and the value split across two continuation lines as two separate encoded words. So `/Subject:.*/` finds an EMPTY subject, and `/^Subject:\s*(.*)$/m` finds only the FIRST encoded word - a silently truncated subject, which is worse. Unfold first (join a line beginning with a space or tab onto the previous one), then RFC 2047-decode **every** encoded word in the result and concatenate. The same applies to any long header, `To` and `From` included.
  279. - **`criteria` is a structured object, never raw IMAP syntax** - the only string accepted is `'ALL'` (the default). Fields: `since`, `before`, `from`, `to`, `subject`, `text`, `body`, `headerName`+`headerValue`, `unseen`, `seen`, `flagged`, `largerThanBytes`, `smallerThanBytes`. `headerName` and `headerValue` are one criterion in two halves and must both be given, because a server answers a half-stated one with a syntax error rather than with a match. **A non-ASCII criterion value is REFUSED** (naming the field): expressing it needs a multi-step `CHARSET UTF-8` literal exchange this transport does not drive, and sending the bytes anyway makes the server match nothing - and zero results is indistinguishable from "there is no such mail", which is a silently wrong answer rather than a missing feature. Filter on an ASCII-safe criterion, or on sender or date, and match accented text yourself after fetching. Mailbox NAMES are unaffected and may be non-ASCII.
  280. - `ctx.mail.mailboxes({...})` -> `[{name, nameEncoding, flags, delimiter}]`. Names are decoded from IMAP's modified UTF-7, so `Beérkezett` arrives readable.
  281. - `ctx.mail.send({from, to, cc, bcc, subject, text, html, attachments, replyTo, headers, inReplyTo, references, ...})` -> `{ok: true, accepted: [...]}`. `to`/`cc`/`bcc` take a string or an array. Structure is chosen for you: text only is `text/plain`, text plus `html` is `multipart/alternative`, and attachments wrap it in `multipart/mixed`. Attachments are `{filename, contentType, base64}`. **`bcc` recipients receive the message but appear in no header of it.** A non-ASCII subject, display name or filename is encoded correctly (RFC 2047, and RFC 2231 for filenames). An address, subject, filename or header containing CR or LF is **refused by name** - that is header injection.
  282. - **CHECK WHICH SMTP PORT YOUR HOST ALLOWS BEFORE WRITING THE FUNCTION. On a DigitalOcean droplet, outbound 25, 465 and 587 are BLOCKED by the provider and 2525 is open.** Measured on ours, and confirmed as the host's policy rather than any mail server's by `smtp.gmail.com:587` and `smtp.sendgrid.net:587` being blocked identically. **CONFIRMED INDEPENDENTLY ON A SECOND, UNRELATED DROPLET**, which is what makes this a property of the host rather than of our box: a consumer measured 25, 465 and 587 blocked to both gmail and sendgrid from their own droplet, with `api.openai.com:443` open as a control and **`smtp.sendgrid.net:2525` OPEN**. **THE COROLLARY THAT MATTERS MORE THAN THE RULE: moving the send out of `ctx.mail` into your own service does NOT escape this.** Both are SMTP from the same host, so nodemailer on your own droplet hits the identical wall and fails the identical way - a seven-second timeout that reads like a wrong credential. The constraint is the PORT, not this API, so "write it myself instead" is not a workaround. And because one provider on 2525 was measured open, a provider that offers no 2525 does not make SMTP impossible either - it makes it a question of WHICH relay, not of whether to use SMTP at all. A send on a blocked port fails as `mail_timeout` **504** after about 7 seconds with `retryable: false` - which is the correct answer and reads exactly like a wrong credential or a dead server, so it is the hardest failure here to diagnose from the error alone. A send over **2525 with STARTTLS works**, verified end to end through the deployed runner (accepted in ~1.3 s, then found by `UID SEARCH` and fetched back). IMAP 993 and 143 are unaffected and open. So **confirm your provider offers 2525** before building, and remember this is a property of the HOST your runner sits on rather than of this API.
  283. - **The sending ACCOUNT is per call, and there is no project-level mailbox or default account.** `host`, `port`, `user`/`userSecret` and `password`/`passwordSecret` are options on every one of the three calls. That is deliberate and it matters when the mailbox and the data have different owners: a function running for a customer's project can send from YOUR OWN identity without the customer's mail system being involved at all, and nothing about the project binds the sender. A consumer sent internal commercial figures through a mailbox living inside their customer's tenant, where the customer's administrator could read them in the Sent folder; the remedy is simply to pass your own connection fields.
  284. - **There is NO idempotency key on `send`, deliberately.** A send is never reported as retryable once the conversation could have reached delivery, because a duplicate e-mail cannot be recalled - so there is nothing for a key to deduplicate against. If you need at-most-once for something like a daily report, the guard is yours: write a sent-marker row before the send and check it on the next tick.
  285. - **Inline images are NOT expressible.** Attachments are `{filename, contentType, base64|text}` with no content-id, and the structure is chosen for you - `text/plain`, `multipart/alternative` with `html`, wrapped in `multipart/mixed` when there are attachments. There is no `multipart/related`, so a `cid:` reference in your HTML has nothing to resolve against. Use an `https` image (most clients block remote images until the recipient allows them), attach the file normally, or leave it out; a `data:` URI is stripped by several clients including Outlook.
  286. - **Mail hosts go through the same SSRF guard as `ctx.fetch`**, so loopback, private and link-local destinations are refused (`egress_blocked`, with the guard's reason) and a function cannot reach a mail server on the API host. The name is resolved **once** and every address it returns is classified, then the approved address is pinned for the connection - re-resolving is the rebinding window. Plaintext (`tls:false, startTls:false`) to anything but a loopback literal is refused as `mail_tls_required`.
  287. - **One run may load at most 4 MiB of mail**, independently of any mailbox size, because a run holds a pooled runtime with its own memory limit. Exceeding it is **422** `mail_too_large` - deliberately not a timeout, because the remedies differ and a caller told "timeout" for an oversized mailbox retries forever.
  288. - **Slugs worth branching on**, each with `details.retryable`: `mail_timeout` **504**, `mail_too_large` **422**, `mail_incomplete` (the server stopped mid-message; retryable, since a peek fetch changed nothing), `mail_rejected` **422** (the server refused permanently, usually a bad recipient or sender - its reply text is included), `mail_server_busy` **503** (a transient 4xx; retryable), `mail_auth_failed` (**never** retryable - repeating a rejected login is how an account gets locked), `mail_tls_untrusted` (the certificate did not verify; never retried and never downgraded), `mail_unreachable` and `mail_unresolvable` (retryable, nothing reached the server). **A send is never reported as retryable** once the conversation could have reached delivery, because a duplicate e-mail cannot be recalled.
  289. - **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.
  290. - `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.
  291. - `.insert(doc)` honours an **`id` inside the document object** - the idiom for an idempotent write.
  292. - `.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.
  293. - `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.
  294. - `ctx.jobs.cancel(id)` - cancel a job that has not been claimed yet. Returns a **boolean**: false when there was nothing cancellable.
  295. - **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.
  296. - `ctx.crypto.hmacSha256(key, data, encoding?)` - HMAC-SHA256, `encoding` being `hex` (default) or `base64`. For verifying a provider's webhook signature.
  297. - `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.
  298. - `ctx.crypto.randomUUID()` - a version 4 UUID.
  299. - `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.
  300. - `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).
  301. - `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.
  302. - `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.
  303. - `Intl.DateTimeFormat` also works inside a function, installed per context.
  304. - **`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.
  305. - **`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.
  306. - **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.
  307. - **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**.
  308. - **`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.
  309. - `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.
  310. - `ctx.log(...)` - captured into the run's `console`, bounded.
  311. **A denied collection access throws a catchable error** naming the collection and the operation, rather than returning an empty result - so a missing grant looks like a failure, not like missing data.
  312. **The return value shapes the response.** An object whose keys are a non-empty subset of `{status, headers, body}` is a response envelope; any other object is sent as a `200` body; an object MIXING envelope keys with other keys **fails the run** rather than being guessed at. Host calls are synchronous, so `await` is optional - it works because awaiting a non-promise is a no-op.
  313. **The id lives in the source, not in the URL.** A script exports `export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' }`, and that `id` is the registry row's identity. `path` records where the author keeps the file and carries no meaning, so moving `kb-search.js` to `lib/search.js` keeps the same row - and the policy an admin granted travels with it.
  314. **Every write is compiled on a runner before it is stored.** The engine that validates is the engine that will execute. A compile failure is **422** `compile_failed` with the error; an `on` block with no id is **422** `missing_function_id`; no healthy runner is **503** `no_runner` and nothing is stored. Code is never stored unvalidated.
  315. **A code push can never widen access.** `policy` is server state: a `policy` field sent with a `POST`/`PUT` body is ignored (not merged, not consulted as a fallback), and `enabled` is likewise preserved, so re-pushing code does not re-enable a function an operator turned off. A first registration inherits the project's default policy, which currently grants **no collection at all** - the function runs, logs and can call out, but reaches no data until an admin grants it a rule.
  316. - `GET /api/v1/projects/{project}/functions` - List functions **without their sources**: `{functions:[{function_id, path, content_hash, descriptor, policy, enabled, valid, last_error, created_at, updated_at}], runners:{configured, healthy}, runs_kept}`. The `runners` counts let a client warn that a write will fail with **503** *before* an author writes a script, rather than only after the push: `configured: 0` is the common first state, because installing the runner package does not switch functions on - the server needs a `functions.runners` list. `runs_kept` is this SERVER's configured run-log retention (`functions.runs_kept`), so a client need not guess the default - but read it as covering `http` and `invoke` runs ONLY. Cron and job runs are appended and trimmed by the RUNNER, under its own `function_runs_kept` in runner.json, which this field cannot see and which ships with a DIFFERENT default (50 against the server's 500) - so on a host that has not set both, this number overstates a cron function's retention tenfold. Retention is a boot config on each binary: it is not settable per function or per project, and no request can change it.
  317. - `POST /api/v1/projects/{project}/functions` `{source, path?}` - Register a new function; the id comes from the validated `on` block, so there is no `function_id` field to send. An id already in use is **409** `function_exists` (PUT it to update).
  318. - `GET /api/v1/projects/{project}/functions/{id}` - Get one function, **including** `source`.
  319. - `PUT /api/v1/projects/{project}/functions/{id}` `{source, path?}` - Push code. The id the script declares must equal the id in the URL; a mismatch is **422** `id_mismatch` (with `error.details.declared` and `error.details.url`) rather than a rename, because the URL would otherwise move code onto another function's policy. A PUT to an unused id registers it (**201**).
  320. - `DELETE /api/v1/projects/{project}/functions/{id}` - Delete the function, its code and its policy.
  321. - `PUT /api/v1/projects/{project}/functions/{id}/policy` `{policy:{rules, origins?, ip_allow?, rate_limit_per_min?, expires_at?}}` **(admin)** - Replace what the function may touch. Same vocabulary as a key scope (`rules` of `{collection, ops}` over `read`/`list`/`search`/`insert`/`update`/`delete`), with one difference: an **empty** rule set is legal and means the function reaches nothing. This is the only route that changes a policy.
  322. - `ip_allow` (array of CIDR ranges or bare addresses, default empty = no restriction) pins the function to caller addresses. **It fails closed**: a non-empty list refuses any request whose address the server could not establish, so a wrong `trusted_proxy_cidrs` refuses everyone rather than the wrong ones. A malformed entry is refused at write time with 422 `validation`; one that somehow reached storage removes only itself and never widens the list. Checked **before** authentication and before the rate limit, so a refused caller cannot spend the function's minute budget - and the refusal writes **no run-log row**, because nothing ran.
  323. - `PUT /api/v1/projects/{project}/functions/{id}/enabled` `{enabled}` - Enable or disable a function.
  324. - `POST /api/v1/projects/{project}/functions/{id}/invoke` `{method?, path?, params?, query?, headers?, body?}` - Run the function once and record the run. Every field is optional: an empty body invokes it with its declared route as the path and `POST` as the method.
  325. **THE BODY IS AN ENVELOPE DESCRIBING THE REQUEST TO SYNTHESISE, NOT THE FUNCTION'S PAYLOAD - and getting that wrong used to answer 200.** A payload goes under `body`:
  326. `curl -XPOST -H 'Authorization: Bearer $KEY' -H 'Content-Type: application/json' -d '{"body":{"day":"2026-10-12"}}' https://host/api/v1/projects/acme/functions/daily-report/invoke`
  327. The function reads that as `ctx.body`. An unrecognised top-level key is **422** `unknown_option`, naming every one of them and listing the accepted set, and a body that is not a JSON object is refused the same way. Until 0.14.0 an unknown key was silently DISCARDED and the call still answered **200**, so a bare `{"day":"2026-10-12"}` ran the function with an EMPTY `ctx.body` and was indistinguishable from a run that had worked - it surfaced only when a caller asked for two different days and got the same day back twice. If you invoke with a payload, check the shape: a 422 now means you were previously getting a run of your function's DEFAULT input, not of the input you sent. A key of the wrong TYPE is not refused - `params` as a string falls back to an empty object, as it always has. Returns **200** whenever the run was *performed*, with `{run_id, ok, status, headers, body, console, duration_ms, error, timed_out, out_of_memory}` - the function's own failure is in that envelope, not in the HTTP status, so "the function returned 500" stays distinguishable from "the invoke could not be performed". A disabled or invalid function is **409**; a runner that cannot be reached is **503** `runner_unreachable`, and the failed attempt is still logged.
  328. - `GET /api/v1/projects/{project}/functions/{id}/logs` - Recorded runs, newest first: `{function_id, runs:[{run_id, function_id, trigger, ok, status, duration_ms, error, console, headers, started_at}]}`. `headers` is omitted when the function set none, and is present so a stored run renders with the same shape as a fresh invoke envelope. `?limit=` defaults to 50.
  329. **A failed run now also carries `failure_kind`, which says WHOSE problem it is.** `function_fault` means the script's own doing (it threw, returned a non-response, blew its memory ceiling, is disabled or will not compile) and is never retried. `runner_fault`, `abandoned` (a runner died holding the job) and `malformed` (a corrupt queue row) are OURS, not yours. `transient_lookup` is a registry read that did not answer; `reclaimed` is a stale claim going back for another attempt, so the job has not failed. The classification was always computed and then discarded, so a failed job recorded only a free-text message - and matching on message text is exactly what nobody should have to do.
  330. **The field is ABSENT on a successful run AND on a server older than this release, so never read its absence as "no failure" - `ok` is the field that answers that.** The names are append-only and will not be respelled; an unrecognised one is a kind added by a newer server, so treat an unknown value as "something failed, cause not known to me" rather than ignoring the run.
  331. `?limit=` is the ONLY parameter: there is no `status` filter, and asking for one is refused 422 rather than silently returning the newest runs of every outcome.
  332. **The log keeps only the newest N runs per function** (trimmed on every write, since there is no scheduler yet), so a limit above N returns N and an old `run_id` eventually stops resolving.
  333. ### Calling a function
  334. - `ANY /fn/{project}/{path}` - **Unauthenticated BY DEFAULT**, and gateable per function since 0.15.0. This is where a published function is served. The project is the first path segment and the rest is matched against that project's `on` routes, so `/fn/acme/kb/hungary` reaches the `acme` function declaring `route: '/kb/:topic'` with `topic = "hungary"`.
  335. - **`auth: 'key'` in the `on` block requires an API key on the call**, sent as `Authorization: Bearer <key>`. The key must authenticate and must be granted the function's project; it is checked by the same code that guards `/api/*`, so a function's gate cannot drift from the rest of the server. No key or an unknown one is **401** `unauthorized` with `WWW-Authenticate: Bearer`; a valid key for a different project is **403** `forbidden`, because re-sending the same credential cannot help. **A missing key and a wrong key answer identically on purpose** - distinguishing them tells someone probing tokens which half of the guess was right.
  336. - `auth: 'public'` is the default and the historical behaviour, so **nothing already deployed changes**. A key sent to a public function is neither required nor rejected.
  337. - **An unrecognised value is REFUSED at push time** (`auth: 'kye'` fails the write), unlike an unknown KEY in the `on` block, which is still ignored so a script written for a newer server keeps loading. A typo must never publish a function its author believed was gated.
  338. - **On a server older than 0.15.0 this key is IGNORED and the function is public, silently.** That is the one place the forward-compatibility rule cuts against safety, so check the server version before treating `auth` as the only gate on something sensitive.
  339. - The key is used for the gate and is **not** forwarded to the function - `Authorization` has always been stripped - so a function cannot see, log or reuse the caller's credential.
  340. - **A key-gated function (`auth: 'key'`) AUTHENTICATES the caller and grants them NOTHING - so send your LEAST privileged key, not one scoped to the collections the function reads.** The function still reads and writes under its own stored policy, exactly as it does when public; the key only answers "may this caller invoke the route at all". A key with an empty rule set works and is the right choice. Worth stating because the natural guess is the opposite - that a function reading `kb_facts` needs a caller key carrying `search` on `kb_facts` - and guessing that way over-grants a credential that is, by design, going into a third-party tool configuration. Reported by a consumer who used a least-privileged key, found it worked, and pointed out that nothing said so.
  341. **Order the rollout header-first.** Put the `Authorization` header into the calling tool, confirm it works against the still-ungated route, and only then set `auth: 'key'`. Reversed, the route answers 401 for however long it takes someone to notice - and in front of an assistant or voice agent that presents as "it does not know anything" rather than as an auth failure.
  342. - **A function policy may pin the route to caller ADDRESSES** (`ip_allow`, 0.18.2+). Outside the list is **403** `ip_not_allowed`. Four properties, none of them guessable:
  343. - **It is checked FIRST**, ahead of the `auth: 'key'` gate and ahead of the rate limit. So a caller who is not permitted to be here cannot spend the function's minute budget, and cannot have a token checked.
  344. - **The refusal writes NO run-log row**, because nothing ran. That matters if you currently gate a public function with a token compared inside the script: a script-side check RUNS the function first, so every wrong-token request appends a row to your own run log, and a sustained flood evicts your real runs. An address gate refuses before the runner is involved.
  345. - **It fails closed.** A non-empty list refuses any request whose address the server could not establish, so a wrong `trusted_proxy_cidrs` in global settings refuses *everyone* rather than the wrong ones.
  346. - **The message does not echo your address back.** It is in the server's own access log for an operator to read; reflecting it would hand a prober a free "what do you think my address is" oracle. Ask an operator rather than guessing from the response.
  347. - **The function's `rate_limit_per_min` policy now applies to CALLS on this route** (since 0.15.0), not only to the function's data access. `0` means unlimited, as everywhere else. Over the ceiling is **429** `rate_limited` with `Retry-After: 60`. Three things worth knowing:
  348. - **The two ceilings are counted SEPARATELY against the same number.** A limit of 60 means up to 60 calls a minute AND up to 60 data operations a minute; it does not mean a function doing three reads per call gets 15 calls. Adding a read to a script therefore cannot lower its own request ceiling.
  349. - **The ceiling is per FUNCTION, not per caller.** It bounds the DAMAGE - mail sent, paid API calls made, on the tenant's quota and sender reputation - rather than the denial: one abusive caller can still exhaust a public function's minute and shut out legitimate ones. Per-caller limiting needs an identity, which is what `auth: 'key'` gives you and an anonymous request does not have.
  350. - **A refused call is not written to the run log.** Nothing ran, so there is no run to record - and logging refusals would let an unauthenticated caller append a database row per request, turning a public URL into a write amplifier against the tenant's own storage.
  351. - The function chooses the response: its returned `status`, `headers` and `body` are sent as-is. Returning a plain object with none of those keys sends it as a `200` body, and an object mixing them with other keys **fails the run** rather than being guessed at.
  352. - A path matching no function is **404**; a path that matches but not for this method is **405** with an `Allow:` header. Disabled and invalid functions are simply absent, so they are **404** too - a public caller learns nothing about what a project contains.
  353. - A function that threw is **500**, a wall-time timeout is **504** `function_timeout`, exceeding the memory ceiling is **500** `function_out_of_memory`, and no healthy runner is **503** `runner_unavailable` with `Retry-After`. **The function's error text is never returned** - a stack trace on an open endpoint is an information leak. The response carries `error.details.run_id`, and the message is in `GET .../functions/{id}/logs`.
  354. - Request `Cookie`, `Authorization`, `Proxy-Authorization` and `X-Captcha-Token` headers are **not** forwarded to the function. The web UI is served from this same origin, so forwarding `Cookie` would hand a logged-in admin's session to every function author in the project.
  355. - Repeated query parameters collapse to the last value (`?tag=a&tag=b` gives `tag = "b"`), and `HEAD` is not routable.
  356. ## Stats
  357. - `GET /api/v1/projects/{project}/stats` - Per-project stats (collections, document counts). Accessible to any key granted the project.
  358. - `GET /api/v1/stats` - Server-wide stats including `memory_pressure_level`, an `embedding` object with cache telemetry (`cache_size`, `cache_capacity`, `cache_hits`, `cache_misses`, `cache_hit_ratio`, `cache_bytes`), and `db_client_version`/`db_client_commit` (the smartbotic-database client library the dynamic linker actually bound at process startup, not necessarily what the binary was compiled against (2.4.x and 2.11.x share a SONAME, so a mismatched library can load silently and only crash on a later restart)). Admin only.
  359. ## Admin
  360. - `GET /api/v1/admin/readonly` - Get the server-wide (not per-project) read-only lock status: `{readonly, scope:"server", reason?}`. Reflects the database's own authoritative state - it can enter read-only by itself after a degraded/failed recovery, not only via the PUT below, so `readonly:true` does not necessarily mean an operator locked it; `reason` (DB-defined free text) is present only when non-empty. While locked, writes are rejected by the database and surfaced by vectorapi as **503**. Admin only.
  361. - `PUT /api/v1/admin/readonly` `{readonly}` - Set the server-wide read-only lock. Admin only.
  362. ## Ops
  363. Public (no auth required):
  364. - `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.
  365. - `GET /healthz` - Liveness probe; always 200 while the process is running.
  366. - `GET /readyz` - Readiness probe; 200 when the database is reachable, 503 otherwise.
  367. - `GET /openapi.json` - OpenAPI 3.1 machine-readable spec.
  368. - `GET /llms.txt` - This file.
  369. - `GET /docs` - Rendered API reference page (RapiDoc over the spec above).
  370. Session login (used by the web UI):
  371. - `POST /ui/login` `{key}` - Exchange an API key for an HttpOnly session cookie (`svapi_session`). The cookie may be used in place of the `Authorization: Bearer` header for all `/api/v1/*` endpoints.
  372. - `POST /ui/logout` - Invalidate the session and clear the cookie.
  373. - `GET /ui/session` - Return `{ok, admin, projects}` for the caller's current session (cookie or bearer), or **401** when there is none. Sessions are held in memory, so a server restart invalidates every cookie; a client must call this before trusting any locally stored "logged in" state.
  374. ## What a 404 and a 201 now promise (0.18.0)
  375. Two refusals were tightened so a caller's retry decision is safe. Both move a
  376. case from a WRONG permanent answer to a correct retryable one, so neither can
  377. break a caller who retries on status.
  378. - **`POST /api/v1/keys` and `PATCH /api/v1/keys/{id}`** answer **503**
  379. `db_error` rather than succeeding when the service cannot read the key back
  380. afterwards. A **201 is therefore a statement that the key EXISTS and will
  381. authenticate**, not merely that the write was accepted. Nothing is handed out
  382. on the 503, so retrying is safe and is the right response. This closes a case
  383. where a write visible to the store but not to the read path would have
  384. returned a working-looking secret that could never authenticate - silent,
  385. permanent, and indistinguishable from success.
  386. - **`DELETE /api/v1/projects/{project}/settings` and
  387. `DELETE /api/v1/projects/{project}/secrets/{name}`** answer **503** on a
  388. database failure where they previously answered **404**. A 404 from those
  389. routes now means the thing is genuinely absent and is safe to treat as final.
  390. The old behaviour conflated "no such thing" with "the call failed", and a 404
  391. is unretryable by design for a careful client, so a transient failure became
  392. permanent.