Parcourir la source

fix: idempotent index drops, no inherited constraints, Intl in the runner

A drop is idempotent at the database, so `false` from dropIndex /
dropCompositeUniqueIndex never means "no such index" - it means the call
itself failed: a read-only database, a config write that did not land, or a
dead connection. Both drop handlers mapped it to 404, which would have told a
caller their constraint was gone while it was still being enforced. They now
answer 503, and a drop naming nothing existing is a plain 200.

dropCollection does not undeclare a collection's indexes, so a collection
created under a recycled name inherited constraints nobody declared: a
legitimate write refused as a duplicate, and the new owner's own POST /indexes
reporting already_existed instead of validating their data. Collection-create
(the invisible-orphan drop) and collection-delete now undeclare first.

The ApiFixture suite could not clean a persistent database for the same two
reasons, so it purges each project's indexes before its collections. This was
invisible against packaging/devstack, whose database is new every run.

Also in this change: Intl.DateTimeFormat in the runner (installed per context
beside console, UTC answered in-shim and other zones through one host call),
ctx.* increment, the documents_util and index_request seams with their own
tests, and host_prelude_test.cpp finally wired to a build target - it was
committed in 4c4abcc with no target and had been compiling nothing since.

api/openapi.json and api/llms.txt updated for the drop semantics.
fszontagh il y a 1 mois
Parent
commit
7732f1ccaa

+ 8 - 3
api/llms.txt

@@ -75,6 +75,9 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 - `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
 
   **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` and is not available on a `kind=vector` collection (**422** `conditional_unsupported` for both): the version-checked write has no expiry field, and it rewrites the whole document, which would drop the stored embedding.
+- `POST  /api/v1/projects/{project}/collections/{name}/documents/{id}/increment` `{field: n, ...}` (or `{data:{...}}`) - **Atomic increment.** Adds each number to the named field in ONE locked server-side read-modify-write, so concurrent increments cannot lose each other. Dotted keys address nested fields (`counts.sent`). Returns **200** `{id, values}` where `values` holds the NEW value of every field you named. An absent or null field counts as 0. Integer + integer stays an integer (overflow is refused); anything else becomes a double. A field holding a non-number is **422** `validation` and **nothing at all is applied** - the whole set applies or none of it does. Needs the `update` grant (it is a write, so a read-only scope gets **403**); it is a separate route rather than a flag on PATCH because `{"calls":1}` means "set calls to 1" on PATCH and "add 1 to calls" here.
+
+  **It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
 - `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.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents` - Find documents. 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.
 - `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).
@@ -100,8 +103,10 @@ Additional query params: `limit` (default 20), `offset` (default 0), `sort` (fie
 Project-scoped, under a collection. Index create/drop require a full (non-scoped) key with project access - scoped keys cannot manage indexes.
 
 - `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.
-- `GET    /api/v1/projects/{project}/collections/{name}/indexes` - List indexes: `{indexes:[{field, distinct_values, entries, unique}]}`.
-- `DELETE /api/v1/projects/{project}/collections/{name}/indexes/{field}` - Drop an index.
+- `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.
+- `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.
+- `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.
+- `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:[...]}`.
 - `GET    /api/v1/projects/{project}/collections/{name}/indexes/{field}/values` - Distinct values with counts: `{values:[{value, count}]}`. Index-dependent by design (not an error): returns an empty list for a field with no index and for array-valued fields, whose index keys are elements rather than values. Query params: `limit` (1-1000, default 100), `order` (`asc`|`desc`, default `asc`; use `order=desc&limit=1` for the maximum). Follows the collection's read grant.
 
 ## Relations (admin)
@@ -196,7 +201,7 @@ export default async function (ctx) {
 
 `ctx` carries the trigger: `method`, `path`, `params` (the `:name` captures), `query`, `headers`, `body`. Repeated query keys collapse to the last value.
 
-- `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.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.
+- `ctx.collections(name)` - a chainable builder. `.filter('field:op:value')`, `.limit(n)`, `.offset(n)`, `.sort('field')` or `.sort('-field')` for descending, then a terminal: `.find()` returns an **array**, `.get(id)` returns the document or **null**, `.insert(doc)` returns `{id}`, `.update(id, doc)` returns `{id}`, `.patch(id, fields)` returns `{id, version}`, `.increment(id, {field: n})` returns the **new values** object (the same atomic increment as the HTTP route, needing the `update` grant; a missing document throws), `.delete(id)` returns `{deleted}`. Filters use the same `field:op:value` grammar as `?filter=`, parsed by the same code and evaluated by the database, so a filter means the same thing here as over HTTP.
 - Vector collections additionally take `.search({query_text|query_vector, top_k, min_score, filters})`, returning an **array** of hits, and `.store({text|vector, metadata})`. Embedding resolves through the normal precedence, so a project's provider override applies.
 - `ctx.fetch(url, {method, headers, body})` - outbound HTTP, **SSRF-guarded**: loopback, private and link-local destinations are refused, which means a function cannot call this API back. The refusal is reported in the run's console rather than as a network error.
 - `ctx.env.<NAME>` - secrets for THIS project only, from two merged sources: the project's own secrets set over the API (see "Project secrets") and the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). A host variable wins over a stored secret of the same name. Never another project's, and never the runner's own configuration.

+ 144 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.5.0",
+    "version": "0.5.1",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -1009,6 +1009,77 @@
         }
       }
     },
+    "/api/v1/projects/{project}/collections/{name}/documents/{id}/increment": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "name",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Collection name"
+        },
+        {
+          "name": "id",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Document ID"
+        }
+      ],
+      "post": {
+        "summary": "Atomically add to one or more numeric fields",
+        "operationId": "incrementDocument",
+        "description": "Adds each number in the body to the named field in ONE locked server-side read-modify-write, and answers with the new values. Concurrent increments therefore cannot lose each other, which a read-add-write cannot promise however carefully it is version-checked. 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 and NOTHING is applied - the whole set applies or none of it does.\n\nA separate route rather than a flag on PATCH, because a PATCH body and an increment body look identical and mean opposite things: {\"calls\": 1} is \"set calls to 1\" on PATCH and \"add 1 to calls\" here, and one body shape with two meanings decided by a query parameter is how a forgotten parameter silently resets a counter.\n\nAuthorization is the collection's `update` grant: it is a write, so a scope granting only `read` gets 403, and it is specifically an update because the document must already exist. It grants nothing `update` did not - a caller that may replace a document may already set any number to any value.\n\nThe document must exist: this route never creates one, because the starting document is the caller's to describe. The idiom for a counter that may not exist yet is to increment, on 404 POST the document under a fixed id with its starting values, and on 409 duplicate_values (another writer just created it) increment again.",
+        "requestBody": {
+          "required": true,
+          "description": "The deltas, as field -> number. A dotted key addresses a nested field (`counts.sent`). Accepts the same two body shapes as a document write: the deltas on their own, or wrapped as {\"data\": {...}} - and `data` beside any other top-level key is 422 ambiguous_body, exactly as on POST/PUT/PATCH.",
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "minProperties": 1,
+                "additionalProperties": { "type": "number" },
+                "example": { "calls": 1, "minutes": 3.5 }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Applied; the new values of every field named",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "id": { "type": "string" },
+                    "values": {
+                      "type": "object",
+                      "additionalProperties": { "type": "number" },
+                      "description": "The NEW value of each field that was incremented. Returned in the response rather than left to a follow-up GET: a caller that has to re-read to learn its own result has lost the atomicity it came here for.",
+                      "example": { "calls": 18, "minutes": 61.5 }
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - the collection's `update` grant is required" },
+          "404": { "description": "No such collection, or no such document (this route never creates one)" },
+          "409": { "$ref": "#/components/responses/Conflict" },
+          "422": { "description": "Validation error: an empty body, a non-numeric or non-finite delta, a field path with an empty segment, or `data` beside other top-level keys. Nothing was applied." },
+          "503": { "description": "Database unavailable, read-only, or under memory pressure" }
+        }
+      }
+    },
     "/api/v1/projects/{project}/collections/{name}/documents/{id}/delete-impact": {
       "parameters": [
         {
@@ -1090,6 +1161,41 @@
           "description": "Collection name"
         }
       ],
+      "delete": {
+        "summary": "Drop a composite unique constraint",
+        "operationId": "dropCompositeUniqueIndex",
+        "description": "Drops the composite unique constraint over the EXACT set of fields named. Repeat the `fields` parameter once per field; order does not matter. The field list lives in a query parameter rather than a path segment because joining it would need a separator that no field name may contain, and a reserved segment under .../indexes/{field} would shadow a real field of that name. Single-field indexes are dropped with DELETE .../indexes/{field} instead. Requires a full (non-scoped) key with project access; scoped keys cannot manage indexes.",
+        "parameters": [
+          {
+            "name": "fields",
+            "in": "query",
+            "required": true,
+            "explode": true,
+            "style": "form",
+            "schema": { "type": "array", "items": { "type": "string" }, "minItems": 2 },
+            "description": "Every field of the composite constraint, one `fields` parameter each. An empty or single-field list is 422: this route never means \"drop everything\"."
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "Constraint dropped, or already absent - the drop is idempotent",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "dropped_fields": { "type": "array", "items": { "type": "string" } }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - project access required; scoped keys cannot manage indexes" },
+          "422": { "description": "Validation error (fields missing, repeated, or naming fewer than two fields)" },
+          "503": { "description": "The database did not apply the drop" }
+        }
+      },
       "post": {
         "summary": "Declare a field index, optionally unique; backfills existing rows",
         "description": "Backfills existing rows as part of the call, so the index is usable immediately once this returns. Idempotent: re-declaring an index that already exists on `field` reports already_existed:true instead of erroring. Requires a full (non-scoped) key with project access; scoped keys cannot manage indexes.",
@@ -1099,6 +1205,8 @@
           "content": {
             "application/json": {
               "schema": {
+                "description": "Either a single-field index (`field`) or a composite unique constraint (`fields`). The two are two spellings of one request and are mutually exclusive: a body carrying BOTH is 422 ambiguous_body, never resolved by precedence.",
+                "oneOf": [ {
                 "type": "object",
                 "properties": {
                   "field": { "type": "string" },
@@ -1109,6 +1217,25 @@
                   }
                 },
                 "required": ["field"]
+                }, {
+                  "type": "object",
+                  "description": "A COMPOSITE unique constraint: no two documents may hold the same COMBINATION of these fields, e.g. [\"chat_id\", \"file_unique_id\"]. A document in which ANY of the fields is absent or null does not participate, which is the SQL rule for a NULL in a unique key. Declaring it over existing duplicates fails with 409 duplicate_values and up to five colliding document ids in error.details.duplicate_examples. It backs no query: it is a constraint, not an index a filter can use.",
+                  "properties": {
+                    "fields": {
+                      "type": "array",
+                      "items": { "type": "string" },
+                      "minItems": 2,
+                      "uniqueItems": true,
+                      "description": "Two or more field names, each named once. A dotted name addresses a nested field. One field is not a composite - use `field` instead - and a repeated field is refused, because the database identifies a composite by its exact list."
+                    },
+                    "unique": {
+                      "type": "boolean",
+                      "enum": [true],
+                      "description": "Implied and may be omitted. A composite exists only as a unique constraint, so an explicit false is 422 rather than a constraint the caller believes it declined."
+                    }
+                  },
+                  "required": ["fields"]
+                } ]
               }
             }
           }
@@ -1121,6 +1248,11 @@
                 "schema": {
                   "type": "object",
                   "properties": {
+                    "fields": {
+                      "type": "array",
+                      "items": { "type": "string" },
+                      "description": "Returned instead of `field` when a composite constraint was declared."
+                    },
                     "field": { "type": "string" },
                     "unique": { "type": "boolean" },
                     "rows_indexed": { "type": "integer" },
@@ -1148,6 +1280,17 @@
                 "schema": {
                   "type": "object",
                   "properties": {
+                    "composite_unique": {
+                      "type": "array",
+                      "description": "The composite unique constraints declared on the collection. A separate key rather than extra entries in `indexes`, which keeps exactly its existing shape: a composite backs no query, so it has no distinct_values or entries, and it is named by a field LIST rather than by a field.",
+                      "items": {
+                        "type": "object",
+                        "properties": {
+                          "fields": { "type": "array", "items": { "type": "string" } },
+                          "unique": { "type": "boolean", "enum": [true] }
+                        }
+                      }
+                    },
                     "indexes": {
                       "type": "array",
                       "items": {

+ 19 - 0
runner/CMakeLists.txt

@@ -146,6 +146,25 @@ if(BUILD_TESTS)
         runner_protocol OpenSSL::Crypto GTest::gtest_main)
     gtest_discover_tests(test_job_worker PROPERTIES TIMEOUT 120)
 
+    # The prelude's argument checks, driven through the real engine with
+    # recording bindings standing in for the native ones. This file was
+    # committed without a target and so had never been compiled - exactly the
+    # class of miss that let the job worker ship unwired.
+    add_executable(test_host_prelude tests/host_prelude_test.cpp)
+    target_compile_definitions(test_host_prelude PRIVATE
+        SVAPI_HOST_PRELUDE_PATH="${CMAKE_CURRENT_SOURCE_DIR}/src/host_prelude.js")
+    target_link_libraries(test_host_prelude PRIVATE runner_core GTest::gtest_main)
+    gtest_discover_tests(test_host_prelude PROPERTIES TIMEOUT 120)
+
+    # Intl.DateTimeFormat against real time zone answers. timezone.cpp is pure,
+    # so it compiles in directly rather than dragging in the database client.
+    add_executable(test_intl_shim
+        tests/intl_shim_test.cpp
+        ${SVAPI_SRC_DIR}/functions/timezone.cpp)
+    target_include_directories(test_intl_shim PRIVATE ${SVAPI_SRC_DIR})
+    target_link_libraries(test_intl_shim PRIVATE runner_core GTest::gtest_main)
+    gtest_discover_tests(test_intl_shim PROPERTIES TIMEOUT 120)
+
     # ctx.env scoping and the runner's own authentication: both pure, and both
     # tenancy boundaries, so they are tested without an engine or a database.
     add_executable(test_runner_env_auth

+ 21 - 6
runner/config/runner.json

@@ -1,15 +1,30 @@
 {
   "log_level": "info",
-  "http": { "bind_address": "127.0.0.1", "port": 8090, "read_timeout_sec": 30, "auth_token": "" },
-  "database": { "address": "localhost:9004" },
+  "http": {
+    "bind_address": "127.0.0.1",
+    "port": 8090,
+    "read_timeout_sec": 30,
+    "auth_token": ""
+  },
+  "database": {
+    "address": "localhost:9004"
+  },
   "runtime": {
     "pool_size": 4,
     "memory_limit_bytes": 134217728,
-    "max_http_wall_time_ms": 2000,
+    "max_http_wall_time_ms": 15000,
     "max_job_wall_time_ms": 120000,
-    "default_wall_time_ms": 0,
+    "default_wall_time_ms": 2000,
     "project_budget_ttl_sec": 15,
     "max_stack_bytes": 524288,
-    "bytecode_cache_entries": 64
-  }
+    "bytecode_cache_entries": 64,
+    "job_pool_size": 4
+  },
+  "jobs": {
+    "enabled": false,
+    "workers": 0,
+    "max_attempts": 5,
+    "stale_claim_sec": 300
+  },
+  "function_runs_kept": 50
 }

+ 56 - 0
runner/src/host_context.cpp

@@ -2,6 +2,7 @@
 
 #include "collection_registry.hpp"
 #include "db_errors.hpp"
+#include "documents_util.hpp"
 #include "embedding_cache.hpp"
 #include "embeddings.hpp"
 #include "errors.hpp"
@@ -163,6 +164,11 @@ std::optional<KeyOp> keyOpForDbOp(const std::string& op) {
     if (op == "insert") return KeyOp::Insert;
     if (op == "update") return KeyOp::Update;
     if (op == "patch")  return KeyOp::Update;
+    // An increment is an update: it writes, so a read-only policy never reaches
+    // it, and it creates nothing (the database requires the document to exist).
+    // A policy that may replace a document may already set any number to any
+    // value, so this grants nothing `update` did not.
+    if (op == "increment") return KeyOp::Update;
     if (op == "delete") return KeyOp::Delete;
     if (op == "search") return KeyOp::Search;
     if (op == "store")  return KeyOp::Insert;
@@ -367,6 +373,27 @@ nlohmann::json stripDbMetadata(nlohmann::json doc) {
     return doc;
 }
 
+/// The deltas a `.increment(id, {field: n})` call carries.
+///
+/// No `{"data": ...}` unwrapping, for the reason documentFrom() gives: that
+/// shape exists because an HTTP body has no other way to say "this is the
+/// payload", while the builder names the argument. The rules the values must
+/// obey come from validateIncrementDeltas(), the same function the HTTP route
+/// uses, so a function author and an HTTP caller are refused identically.
+///
+/// `id` and the database's read-only metadata are dropped rather than refused,
+/// matching documentFrom(): a script that read a document, computed a delta per
+/// field and passed the result would otherwise be told off for the `_version`
+/// the database itself attached.
+nlohmann::json incrementDeltasFrom(const nlohmann::json& payload) {
+    if (!payload.is_object() || !payload.contains("deltas"))
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "the increments must be an object of field -> number");
+    nlohmann::json deltas = stripDbMetadata(payload.at("deltas"));
+    if (deltas.is_object()) deltas.erase("id");
+    return validateIncrementDeltas(std::move(deltas));
+}
+
 
 // --- ctx.jobs --------------------------------------------------------------
 
@@ -1017,6 +1044,7 @@ struct HostContext::Impl {
         if (op == "insert") return insert(collection, payload);
         if (op == "update") return update(collection, payload);
         if (op == "patch")  return patch(collection, payload);
+        if (op == "increment") return increment(collection, payload);
         if (op == "delete") return remove(collection, payload);
         if (op == "search") return search(collection, payload);
         return store(collection, payload);
@@ -1151,6 +1179,34 @@ struct HostContext::Impl {
         return nlohmann::json{{"id", id}, {"version", v}};
     }
 
+    /// An atomic counter bump: one locked server-side read-modify-write.
+    ///
+    /// This is the call a function reaches for instead of get-add-put, and the
+    /// reason it exists here at all: two runs of the same function racing on one
+    /// counter is the normal case, not the rare one, and a read-modify-write
+    /// loses increments however carefully it is version-checked.
+    ///
+    /// Returns the new values themselves rather than `{id, version}` like the
+    /// other writes: the values are what the caller came for, and making it
+    /// read `.values` would be an envelope around the only thing in it. The
+    /// HTTP route does wrap them, because an HTTP response has to carry the id
+    /// it was addressed to.
+    nlohmann::json increment(const std::string& collection, const nlohmann::json& payload) {
+        const std::string id = documentId(payload);
+        nlohmann::json deltas = hostdetail::incrementDeltasFrom(payload);
+        meta(collection);
+        smartbotic::database::Client::FailureDetail failure;
+        auto values = db.client().increment(qualify(config.project, collection), id, deltas,
+                                            failure, writeActor());
+        // A missing document is an error here, not a null as .get() returns: a
+        // counter the caller believes it bumped and did not is a wrong number
+        // nobody notices, while an absent document is simply absent. The
+        // documented idiom is to catch it, insert the starting document under
+        // the fixed id, and increment again.
+        if (!values) throw apiErrorFor(failure, "no such document");
+        return *values;
+    }
+
     /// A version-checked patch: ONE server-side call that merges and checks
     /// the version together.
     ///

+ 28 - 0
runner/src/host_prelude.js

@@ -171,6 +171,18 @@
         return __hostDb(name, 'patch', { id: id, doc: fields,
                                          ttl_seconds: o.ttl_seconds, ifVersion: o.ifVersion });
       },
+      // One locked server-side read-modify-write, so two runs racing on the
+      // same counter cannot lose each other - which get-add-put does however
+      // carefully it is version-checked. Returns the NEW values object, not
+      // {id, ...}: the values are the point of the call and the caller already
+      // has the id. No write options - an increment is not a replace, so there
+      // is no expiry to carry and nothing to compare-and-set against.
+      increment: function (id, deltas) {
+        need(typeof id === 'string' && id.length > 0, '.increment() takes a document id');
+        need(isPlainObject(deltas),
+             '.increment() takes an object of field -> number, e.g. { calls: 1 }');
+        return __hostDb(name, 'increment', { id: id, deltas: deltas });
+      },
       // Legal as a method name since ES5, and it is the name the design shows.
       delete: function (id) {
         need(typeof id === 'string' && id.length > 0, '.delete() takes a document id');
@@ -495,6 +507,22 @@
     }
   };
 
+  // --- Intl.DateTimeFormat's zone data --------------------------------------
+
+  // `Intl` itself is installed by the engine core, so that a module which
+  // builds a formatter at load time can be registered at all. What the core
+  // cannot supply is the tz database, which lives behind __hostTime - so the
+  // shim exposes a one-shot hook and we hand the binding over here.
+  //
+  // The hook is REMOVED afterwards. __hostTime stays a parameter of this
+  // function, never a global, and leaving a hook that accepts a replacement
+  // date source would be a way for user code to reach around the only thing
+  // the shim and ctx.time agree on.
+  if (typeof globalThis.__svapiBindIntlTime === 'function') {
+    globalThis.__svapiBindIntlTime(__hostTime);
+    delete globalThis.__svapiBindIntlTime;
+  }
+
   // --- ctx.log ---------------------------------------------------------------
 
   ctx.log = function () {

+ 469 - 0
runner/src/intl_shim_js.inc

@@ -0,0 +1,469 @@
+// A minimal `Intl.DateTimeFormat`, installed into EVERY fresh context.
+//
+// This file is JavaScript wrapped in a C++ raw string literal so js_runtime.cpp
+// can embed it with a plain #include: the engine carries the shim in the
+// binary, with no runtime file beside it that could be swapped for another one.
+//
+// WHY it exists: quickjs-ng ships no Intl and no ICU, so `new
+// Intl.DateTimeFormat(...)` is a TypeError. Real-world handlers build a
+// formatter at MODULE SCOPE, which means the throw happens while the module is
+// being evaluated to read its `on` descriptor - so the function cannot even be
+// registered, let alone run. A native `ctx.time` already covers zone-correct
+// formatting, but it does not help code that was written against Intl.
+//
+// WHY it is installed in the engine core rather than in the host prelude: the
+// prelude is installed per RUN, and not at all when a module is evaluated only
+// to read its descriptor. A shim that is meant to survive module load time has
+// to be there before the module is.
+//
+// WHY it still needs the host: zone maths belongs to the tz database, which
+// lives behind the native `__hostTime` binding. The prelude hands that binding
+// in through a one-shot hook and then removes the hook. The ONE thing this file
+// does on its own is UTC, because Date's own getUTC* accessors already answer
+// that without any zone database - which is what makes a module that formats a
+// UTC timestamp at load time registrable.
+//
+// WHY the names are here rather than fetched from the native formatter: the
+// civil fields come from the host (`__hostTime('parts')`), but month and
+// weekday names would cost a second host call per format() and would make the
+// no-host UTC path impossible. The tables below are therefore a deliberate
+// second copy of the ones in host_context.cpp; `ctx.time.format()` keeps using
+// those, and the two must be edited together. The Hungarian ABBREVIATIONS
+// differ on purpose: `ctx.time.format`'s `MMM` is a three-byte slice of the
+// long name, while Intl semantics want the real abbreviation ("szept.").
+//
+// Deliberately NOT here: Intl.NumberFormat and everything else under Intl.
+// Absent rather than present-and-throwing, so `typeof Intl.NumberFormat ===
+// 'undefined'` works as a feature test and a polyfill can install its own.
+R"JS(
+(function () {
+  'use strict';
+
+  const g = globalThis;
+
+  // Never shadow a real implementation. If quickjs is ever built with Intl, or
+  // a tenant's bundle ships a polyfill that ran first, that one is better than
+  // this one and keeps the field.
+  const existing = typeof g.Intl === 'object' && g.Intl !== null ? g.Intl : null;
+  if (existing !== null && typeof existing.DateTimeFormat === 'function') return;
+
+  // `__hostTime(op, payload)`, handed in by the host prelude once per run. Null
+  // while a module is evaluated for its descriptor, which is exactly the case
+  // the UTC path exists for.
+  let timeBackend = null;
+
+  const kDefaultLocale = 'en';
+
+  const kNames = {
+    en: {
+      months: ['January', 'February', 'March', 'April', 'May', 'June',
+               'July', 'August', 'September', 'October', 'November', 'December'],
+      monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
+      monthsNarrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
+      weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
+      weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
+      weekdaysNarrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
+      am: 'AM',
+      pm: 'PM'
+    },
+    // Lowercase, because Hungarian does not capitalise month or day names: a
+    // capitalised "Október" mid-sentence is a spelling mistake, and an author
+    // who wants it capitalised can do that in one line while one who wants it
+    // correct cannot undo it.
+    hu: {
+      months: ['január', 'február', 'március', 'április', 'május', 'június',
+               'július', 'augusztus', 'szeptember', 'október', 'november', 'december'],
+      monthsShort: ['jan.', 'febr.', 'márc.', 'ápr.', 'máj.', 'jún.',
+                    'júl.', 'aug.', 'szept.', 'okt.', 'nov.', 'dec.'],
+      monthsNarrow: ['J', 'F', 'M', 'Á', 'M', 'J', 'J', 'A', 'Sz', 'O', 'N', 'D'],
+      weekdays: ['vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat'],
+      weekdaysShort: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
+      weekdaysNarrow: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
+      am: 'de.',
+      pm: 'du.'
+    }
+  };
+
+  function pad2(v) {
+    const s = String(v);
+    return s.length >= 2 ? s : '0' + s;
+  }
+
+  // Language subtag only, case-insensitively: "hu-HU" and "hu" get the same
+  // names, because that is all the data there is. A tag whose language is not
+  // one of them RESOLVES TO THE DEFAULT rather than throwing - throwing while a
+  // module is being loaded is the exact failure this shim exists to remove, and
+  // the real API also falls back to a default locale when it cannot match.
+  function matchLocale(tag) {
+    if (typeof tag !== 'string') return null;
+    const sep = tag.search(/[-_]/);
+    const lang = (sep < 0 ? tag : tag.slice(0, sep)).toLowerCase();
+    return Object.prototype.hasOwnProperty.call(kNames, lang) ? lang : null;
+  }
+
+  function resolveLocale(locales) {
+    if (locales === undefined || locales === null) return kDefaultLocale;
+    const list = Array.isArray(locales) ? locales : [locales];
+    for (let i = 0; i < list.length; i++) {
+      const hit = matchLocale(list[i]);
+      if (hit !== null) return hit;
+    }
+    return kDefaultLocale;
+  }
+
+  function optionValue(options, name, allowed, dflt) {
+    const v = options[name];
+    if (v === undefined || v === null) return dflt;
+    const s = String(v);
+    // The real API throws RangeError for a value outside the enumeration, and
+    // an author who wrote month:'2digit' wants to hear about it. This is a typo
+    // in a literal, not data: it cannot be fixed by being lenient.
+    if (allowed.indexOf(s) < 0)
+      throw new RangeError('Intl.DateTimeFormat: ' + name + ' must be one of ' +
+                           allowed.join(', ') + "; got '" + s + "'");
+    return s;
+  }
+
+  const kNumeric = ['numeric', '2-digit'];
+  const kWidth = ['numeric', '2-digit', 'long', 'short', 'narrow'];
+  const kText = ['long', 'short', 'narrow'];
+
+  function toEpochMs(value) {
+    if (value === undefined) return Date.now();
+    const ms = value instanceof Date ? value.getTime() : Number(value);
+    if (typeof ms !== 'number' || !isFinite(ms))
+      throw new RangeError('Intl.DateTimeFormat.format: invalid time value');
+    return Math.floor(ms);
+  }
+
+  // Civil fields in a zone. UTC is answered here; everything else is the tz
+  // database's answer, reached through the host so that a function, a cron
+  // schedule and ctx.time can never disagree about what 08:00 in a zone means.
+  function civilParts(epochMs, zone) {
+    if (zone === 'UTC') {
+      const d = new Date(epochMs);
+      return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(),
+               hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(),
+               weekday: d.getUTCDay(), offsetSec: 0, dst: false, abbrev: 'UTC' };
+    }
+    if (timeBackend === null) {
+      // Not a RangeError: the zone may be perfectly valid, the data just is not
+      // reachable from where this code is running. Said plainly, because the
+      // author's next question is "why does it work in the handler".
+      const e = new Error("Intl.DateTimeFormat: zone data for '" + zone + "' is not available " +
+                          'while a module is being loaded; format inside the handler, or use ' +
+                          "timeZone:'UTC'");
+      e.code = 'intl_no_zone_data';
+      throw e;
+    }
+    return timeBackend('parts', { epochMs: epochMs, zone: zone });
+  }
+
+  function offsetText(offsetSec) {
+    const sign = offsetSec < 0 ? '-' : '+';
+    const abs = offsetSec < 0 ? -offsetSec : offsetSec;
+    return 'GMT' + sign + pad2(Math.floor(abs / 3600)) + ':' + pad2(Math.floor((abs % 3600) / 60));
+  }
+
+  // --- option bag -> internal slots -----------------------------------------
+
+  function readOptions(locales, options) {
+    if (options !== undefined && options !== null &&
+        (typeof options !== 'object' || Array.isArray(options)))
+      throw new TypeError('Intl.DateTimeFormat: options must be an object');
+    const o = options === undefined || options === null ? {} : options;
+
+    const locale = resolveLocale(locales);
+
+    let zone = o.timeZone === undefined || o.timeZone === null ? 'UTC' : String(o.timeZone);
+    // Case-insensitive only for the names that mean UTC, the one zone spelled a
+    // dozen ways. Every other name goes to the tz database as written, which is
+    // the only thing that can judge it.
+    const upper = zone.toUpperCase();
+    if (upper === 'UTC' || upper === 'GMT' || upper === 'ETC/UTC' || upper === 'ETC/GMT' ||
+        upper === 'Z')
+      zone = 'UTC';
+
+    const internal = {
+      locale: locale,
+      timeZone: zone,
+      weekday: optionValue(o, 'weekday', kText, undefined),
+      year: optionValue(o, 'year', kNumeric, undefined),
+      month: optionValue(o, 'month', kWidth, undefined),
+      day: optionValue(o, 'day', kNumeric, undefined),
+      hour: optionValue(o, 'hour', kNumeric, undefined),
+      minute: optionValue(o, 'minute', kNumeric, undefined),
+      second: optionValue(o, 'second', kNumeric, undefined),
+      timeZoneName: optionValue(o, 'timeZoneName',
+                                ['long', 'short', 'shortOffset', 'longOffset'], undefined)
+    };
+
+    // The real API's default when no component at all is requested.
+    const anyComponent = internal.weekday || internal.year || internal.month || internal.day ||
+                         internal.hour || internal.minute || internal.second ||
+                         internal.timeZoneName;
+    if (!anyComponent) {
+      internal.year = 'numeric';
+      internal.month = 'numeric';
+      internal.day = 'numeric';
+    }
+
+    // hourCycle is honoured only for the 12-vs-24 question it actually decides
+    // here; hour12 wins when both are given, as in the real API.
+    let hour12 = internal.locale === 'en';
+    const cycle = optionValue(o, 'hourCycle', ['h11', 'h12', 'h23', 'h24'], undefined);
+    if (cycle !== undefined) hour12 = cycle === 'h11' || cycle === 'h12';
+    if (o.hour12 !== undefined && o.hour12 !== null) hour12 = Boolean(o.hour12);
+    internal.hour12 = hour12;
+    internal.hourCycle = hour12 ? 'h12' : 'h23';
+    return internal;
+  }
+
+  // --- assembly --------------------------------------------------------------
+
+  // formatToParts is the primitive and format() is a join of it, so the two can
+  // never disagree about a separator.
+
+  // `named` says whether the month is being rendered as a word, because two
+  // Hungarian rules turn on it: an all-numeric Hungarian date zero-pads its
+  // month and day ("2026. 01. 15.") while one with a month name does not
+  // ("2026. október 7.").
+  function valueFor(type, style, p, internal, names, named) {
+    const huNumeric = internal.locale === 'hu' && !named;
+    if (type === 'weekday') {
+      const i = ((p.weekday % 7) + 7) % 7;
+      if (style === 'long') return names.weekdays[i];
+      if (style === 'short') return names.weekdaysShort[i];
+      return names.weekdaysNarrow[i];
+    }
+    if (type === 'year')
+      return style === '2-digit' ? pad2(((p.year % 100) + 100) % 100) : String(p.year);
+    if (type === 'month') {
+      if (style === 'long') return names.months[p.month - 1];
+      if (style === 'short') return names.monthsShort[p.month - 1];
+      if (style === 'narrow') return names.monthsNarrow[p.month - 1];
+      return style === '2-digit' || huNumeric ? pad2(p.month) : String(p.month);
+    }
+    if (type === 'day') return style === '2-digit' || huNumeric ? pad2(p.day) : String(p.day);
+    if (type === 'hour') {
+      const h = internal.hour12 ? (p.hour % 12 === 0 ? 12 : p.hour % 12) : p.hour;
+      return style === '2-digit' ? pad2(h) : String(h);
+    }
+    // Minute and second are padded whatever the style says, because that is
+    // what the real API does inside a clock time: "3:5 PM" is not a time.
+    if (type === 'minute') return pad2(p.minute);
+    if (type === 'second') return pad2(p.second);
+    if (type === 'dayPeriod') return p.hour < 12 ? names.am : names.pm;
+    if (type === 'timeZoneName') {
+      if (style === 'shortOffset' || style === 'longOffset') return offsetText(p.offsetSec || 0);
+      return p.abbrev || offsetText(p.offsetSec || 0);
+    }
+    return '';
+  }
+
+  // The separator between two adjacent date fields. English runs them together
+  // with slashes when the month is a number and with words when it is a name;
+  // Hungarian always uses ". ", because "2026. október 7." is one pattern with
+  // or without a named month.
+  function dateSeparator(locale, named, a, b) {
+    // "2026. október 7.": the period belongs to the year, not between a month
+    // name and the day.
+    if (locale === 'hu') return named && a === 'month' ? ' ' : '. ';
+    if (!named) return '/';
+    if (a === 'month' && b === 'day') return ' ';
+    if (a === 'day' && b === 'year') return ', ';
+    return ' ';
+  }
+
+  function buildParts(internal, p) {
+    const names = kNames[internal.locale];
+    const named = internal.month === 'long' || internal.month === 'short' ||
+                  internal.month === 'narrow';
+
+    const date = [];
+    const order = internal.locale === 'hu' ? ['year', 'month', 'day'] : ['month', 'day', 'year'];
+    for (let i = 0; i < order.length; i++) {
+      const t = order[i];
+      if (internal[t])
+        date.push({ type: t, value: valueFor(t, internal[t], p, internal, names, named) });
+    }
+
+    const out = [];
+    function lit(text) { if (text) out.push({ type: 'literal', value: text }); }
+
+    // English puts the weekday first ("Wednesday, October 7, 2026"), Hungarian
+    // last ("2026. október 7., szerda").
+    if (internal.weekday && internal.locale !== 'hu') {
+      out.push({ type: 'weekday',
+                 value: valueFor('weekday', internal.weekday, p, internal, names, named) });
+      if (date.length > 0) lit(', ');
+    }
+
+    for (let i = 0; i < date.length; i++) {
+      if (i > 0) lit(dateSeparator(internal.locale, named, date[i - 1].type, date[i].type));
+      out.push(date[i]);
+    }
+    // Hungarian closes a numbered date field with a period: "2026. 10. 07.",
+    // "2026. október 7.". A trailing year or a named month takes none.
+    if (internal.locale === 'hu' && date.length > 0) {
+      const last = date[date.length - 1].type;
+      if (last === 'day' || (last === 'month' && !named)) lit('.');
+    }
+
+    if (internal.weekday && internal.locale === 'hu') {
+      if (date.length > 0) lit(', ');
+      out.push({ type: 'weekday',
+                 value: valueFor('weekday', internal.weekday, p, internal, names, named) });
+    }
+
+    const time = [];
+    const clock = ['hour', 'minute', 'second'];
+    for (let i = 0; i < clock.length; i++) {
+      const t = clock[i];
+      if (internal[t])
+        time.push({ type: t, value: valueFor(t, internal[t], p, internal, names, named) });
+    }
+    if (time.length > 0) {
+      // English separates the date from the time with a comma, Hungarian with a
+      // space: "2026. 10. 07. 14:00".
+      if (out.length > 0) lit(internal.locale === 'hu' ? ' ' : ', ');
+      for (let i = 0; i < time.length; i++) {
+        if (i > 0) lit(':');
+        out.push(time[i]);
+      }
+      if (internal.hour && internal.hour12) {
+        lit(' ');
+        out.push({ type: 'dayPeriod',
+                   value: valueFor('dayPeriod', undefined, p, internal, names, named) });
+      }
+    }
+
+    if (internal.timeZoneName) {
+      if (out.length > 0) lit(' ');
+      const tz = valueFor('timeZoneName', internal.timeZoneName, p, internal, names, named);
+      out.push({ type: 'timeZoneName', value: tz });
+    }
+    return out;
+  }
+
+  // --- the constructor -------------------------------------------------------
+
+  function DateTimeFormat(locales, options) {
+    // Callable without `new`, as the real one is: a surprising amount of code
+    // writes `Intl.DateTimeFormat(...)` and expects a formatter back.
+    if (!(this instanceof DateTimeFormat)) return new DateTimeFormat(locales, options);
+
+    const internal = readOptions(locales, options);
+
+    // Own properties rather than prototype methods, so `list.map(f.format)`
+    // keeps working: the real API's `format` is a bound function too.
+    this.format = function (date) {
+      const ms = toEpochMs(date);
+      const parts = buildParts(internal, civilParts(ms, internal.timeZone));
+      let s = '';
+      for (let i = 0; i < parts.length; i++) s += parts[i].value;
+      return s;
+    };
+    this.formatToParts = function (date) {
+      const ms = toEpochMs(date);
+      return buildParts(internal, civilParts(ms, internal.timeZone));
+    };
+    this.resolvedOptions = function () {
+      const r = { locale: internal.locale, calendar: 'gregory', numberingSystem: 'latn',
+                  timeZone: internal.timeZone };
+      const fields = ['weekday', 'year', 'month', 'day', 'hour', 'minute', 'second',
+                      'timeZoneName'];
+      for (let i = 0; i < fields.length; i++)
+        if (internal[fields[i]]) r[fields[i]] = internal[fields[i]];
+      // Only meaningful when an hour is being rendered, which is also when the
+      // real API reports them.
+      if (internal.hour) {
+        r.hour12 = internal.hour12;
+        r.hourCycle = internal.hourCycle;
+      }
+      return r;
+    };
+  }
+
+  DateTimeFormat.supportedLocalesOf = function (locales) {
+    if (locales === undefined || locales === null) return [];
+    const list = Array.isArray(locales) ? locales : [locales];
+    const out = [];
+    for (let i = 0; i < list.length; i++) {
+      const hit = matchLocale(list[i]);
+      // The matched base tag, not the request: reporting 'en-GB' would promise
+      // British field order, which this shim does not have.
+      if (hit !== null && out.indexOf(hit) < 0) out.push(hit);
+    }
+    return out;
+  };
+
+  const intl = existing !== null ? existing : {};
+  Object.defineProperty(intl, 'DateTimeFormat',
+                        { value: DateTimeFormat, writable: true, configurable: true });
+  Object.defineProperty(g, 'Intl', { value: intl, writable: true, configurable: true });
+
+  // --- Date.prototype.toLocale* ---------------------------------------------
+  //
+  // Code that reaches for Intl usually reaches for these too. They route
+  // through the same formatter, and FALL BACK to the engine's own
+  // implementation on any failure, so a function that already registers and
+  // already calls toLocaleDateString() cannot start throwing because of this
+  // file.
+
+  function localeMethod(originalName, defaults, relevant) {
+    const original = Date.prototype[originalName];
+    Object.defineProperty(Date.prototype, originalName, {
+      value: function (locales, options) {
+        const ms = this.getTime();
+        if (!isFinite(ms)) return 'Invalid Date';
+        try {
+          const o = options === undefined || options === null ? {} : options;
+          // The real API drops its defaults as soon as the caller asks for any
+          // component of the same kind, so {hour:'2-digit'} does not also get
+          // the default minutes and seconds.
+          let picked = false;
+          for (let i = 0; i < relevant.length; i++)
+            if (o[relevant[i]] !== undefined) { picked = true; break; }
+          const merged = {};
+          if (!picked) for (const k in defaults) merged[k] = defaults[k];
+          for (const k in o)
+            if (Object.prototype.hasOwnProperty.call(o, k)) merged[k] = o[k];
+          return new DateTimeFormat(locales, merged).format(ms);
+        } catch (e) {
+          if (typeof original === 'function') return original.call(this, locales, options);
+          throw e;
+        }
+      },
+      writable: true,
+      configurable: true
+    });
+  }
+
+  const kDateFields = ['weekday', 'year', 'month', 'day'];
+  const kTimeFields = ['hour', 'minute', 'second'];
+  localeMethod('toLocaleDateString', { year: 'numeric', month: 'numeric', day: 'numeric' },
+               kDateFields);
+  localeMethod('toLocaleTimeString', { hour: 'numeric', minute: '2-digit', second: '2-digit' },
+               kTimeFields);
+  localeMethod('toLocaleString',
+               { year: 'numeric', month: 'numeric', day: 'numeric',
+                 hour: 'numeric', minute: '2-digit', second: '2-digit' },
+               kDateFields.concat(kTimeFields));
+
+  // The one-shot hook the host prelude uses to hand in `__hostTime`. Not
+  // enumerable, and the prelude DELETES it once it has been used, so user code
+  // never sees it during a run. It is still present while a module is read for
+  // its descriptor, where there is no host to hand in and nothing to gain from
+  // calling it: the worst a tenant can do is feed its own formatter made-up
+  // civil fields.
+  Object.defineProperty(g, '__svapiBindIntlTime', {
+    value: function (hostTime) {
+      timeBackend = typeof hostTime === 'function' ? hostTime : null;
+    },
+    writable: true,
+    configurable: true
+  });
+})();
+)JS"

+ 56 - 27
runner/src/js_runtime.cpp

@@ -177,6 +177,30 @@ void installConsole(JSContext* ctx) {
     JS_FreeValue(ctx, global);
 }
 
+/// A minimal `Intl.DateTimeFormat`. See the file for the whole rationale; the
+/// short version is that quickjs-ng ships no Intl, real handlers build a
+/// formatter at module scope, and the resulting TypeError happens while the
+/// module is being evaluated to read its descriptor - so the function cannot
+/// even be registered.
+constexpr std::string_view kIntlShim =
+#include "intl_shim_js.inc"
+    ;
+
+/// WHY here rather than in the host prelude: the prelude is installed per run,
+/// and not at all when a module is evaluated only to read its `on` export. A
+/// shim that has to survive module load time belongs to the context, next to
+/// console.
+///
+/// A failure is swallowed on purpose. The shim is an ADDITION: if it ever fails
+/// to evaluate, a tenant must be left exactly where they were - without Intl -
+/// rather than losing a run that never needed it.
+void installIntl(JSContext* ctx) {
+    JSValue result = JS_Eval(ctx, kIntlShim.data(), kIntlShim.size(), "<intl-shim>",
+                             JS_EVAL_TYPE_GLOBAL);
+    if (JS_IsException(result)) JS_FreeValue(ctx, JS_GetException(ctx));
+    JS_FreeValue(ctx, result);
+}
+
 } // namespace
 
 struct JsRuntime::Impl {
@@ -192,6 +216,7 @@ struct JsRuntime::Impl {
         if (!ctx) return nullptr;
         JS_SetContextOpaque(ctx, run_state);
         installConsole(ctx);
+        installIntl(ctx);
         return ctx;
     }
 
@@ -440,7 +465,30 @@ JsResult JsRuntime::run(const JsBytecode& bytecode, const nlohmann::json& ctx_ar
     impl_->armDeadline(budget);
 
     std::string error;
-    if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
+
+    // The ctx object and the host bindings are built BEFORE the module is
+    // evaluated, because module TOP-LEVEL code is user code too: a handler that
+    // builds a date formatter at module scope needs the zone data the bindings
+    // carry, and installing afterwards would leave that one statement running
+    // without it. Nothing about the install depends on the module, and the
+    // bindings are not reachable from the global object, so evaluating the
+    // module second changes nothing else.
+    JSValue arg = toJs(ctx, ctx_arg);
+    if (JS_IsException(arg)) {
+        error = takeException(ctx);
+    } else if (host != nullptr) {
+        // install() decorates this object in place; it may not swap the handle,
+        // which run() owns.
+        JsBindingTarget target;
+        target.js_context = ctx;
+        target.ctx_object = &arg;
+        std::string host_error;
+        if (!host->install(target, host_error))
+            error = host_error.empty() ? "host bindings failed to install" : host_error;
+    }
+
+    JSModuleDef* module = error.empty() ? impl_->evaluateModule(ctx, bytecode, error) : nullptr;
+    if (module != nullptr) {
         JSValue ns = JS_GetModuleNamespace(ctx, module);
         if (JS_IsException(ns)) {
             error = takeException(ctx);
@@ -451,40 +499,21 @@ JsResult JsRuntime::run(const JsBytecode& bytecode, const nlohmann::json& ctx_ar
             } else if (!JS_IsFunction(ctx, fn)) {
                 error = "the module has no default export function";
             } else {
-                JSValue arg = toJs(ctx, ctx_arg);
-                if (JS_IsException(arg)) {
+                JSValue returned = JS_Call(ctx, fn, JS_UNDEFINED, 1, &arg);
+                if (JS_IsException(returned)) {
                     error = takeException(ctx);
+                    JS_FreeValue(ctx, returned);
                 } else {
-                    if (host) {
-                        // install() decorates this object in place; it may not
-                        // swap the handle, which run() owns.
-                        JsBindingTarget target;
-                        target.js_context = ctx;
-                        target.ctx_object = &arg;
-                        std::string host_error;
-                        if (!host->install(target, host_error)) {
-                            error = host_error.empty() ? "host bindings failed to install"
-                                                       : host_error;
-                        }
-                    }
-                    if (error.empty()) {
-                        JSValue returned = JS_Call(ctx, fn, JS_UNDEFINED, 1, &arg);
-                        if (JS_IsException(returned)) {
-                            error = takeException(ctx);
-                            JS_FreeValue(ctx, returned);
-                        } else {
-                            JSValue settled = impl_->await(ctx, returned, error);
-                            if (error.empty()) fromJs(ctx, settled, result.value, error);
-                            JS_FreeValue(ctx, settled);
-                        }
-                    }
+                    JSValue settled = impl_->await(ctx, returned, error);
+                    if (error.empty()) fromJs(ctx, settled, result.value, error);
+                    JS_FreeValue(ctx, settled);
                 }
-                JS_FreeValue(ctx, arg);
             }
             JS_FreeValue(ctx, fn);
         }
         JS_FreeValue(ctx, ns);
     }
+    JS_FreeValue(ctx, arg);
 
     // The handler fires inside a JS frame; the clock catches the case where the
     // deadline passed between two microtasks, with no frame to interrupt.

+ 184 - 6
runner/src/main.cpp

@@ -15,7 +15,10 @@
 #include "function_env.hpp"
 #include "function_jobs.hpp"
 #include "job_worker.hpp"
+#include "function_run_log.hpp"
 #include "project_secret_store.hpp"
+#include <mutex>
+#include <set>
 #include "function_record.hpp"
 #include "runner_auth.hpp"
 #include "function_registry.hpp"
@@ -95,15 +98,28 @@ struct RunnerConfig {
     /// Ceiling for a run an HTTP request triggered. Kept at two seconds: a
     /// client is waiting on it, and vectorapi's read timeout is sized against
     /// this number.
-    int64_t maxWallTimeMs = 2000;
+    /// 15 s, not 2. A project cap can only NARROW this, so a 2000 ms ceiling
+    /// made every per-project cap pointless: no project could raise its own
+    /// limit at all, which is the opposite of what the cap is for. 15 s lets a
+    /// voice tool that has to embed a query fit inside the ~20 s a caller
+    /// typically waits.
+    ///
+    /// It is a CEILING, not a grant: a function gets it only by declaring
+    /// timeoutMs, and defaultWallTimeMs decides what an undeclared one gets.
+    int64_t maxWallTimeMs = 15000;
     /// Ceiling for a run the job queue triggered (cron, database events). Two
     /// minutes, because that is what the work is: an LLM call takes seconds to
     /// tens of seconds and an uncached embedding search has been measured at
     /// 26 s, and none of it has a client waiting on a socket.
     int64_t maxJobWallTimeMs = 120000;
-    /// Applied when a descriptor declares no timeoutMs. 0 = use whichever
-    /// ceiling applies to the run.
-    int64_t defaultWallTimeMs = 0;
+    /// Applied when a descriptor declares no timeoutMs.
+    ///
+    /// Deliberately NOT "use the ceiling". Raising the HTTP ceiling to 15 s
+    /// while this meant the ceiling would hand every existing function 15 s of
+    /// runtime lease it never asked for, and a pool of 2 would be held by two
+    /// slow requests. An undeclared function keeps 2 s; one that needs longer
+    /// says so, and an admin caps the project.
+    int64_t defaultWallTimeMs = 2000;
     /// How long a project's wall-time maximum is cached before it is re-read.
     /// Not subscribed to, unlike the server's settings: one read per project
     /// per interval is nothing, and a per-run read would put two round trips on
@@ -122,6 +138,9 @@ struct RunnerConfig {
     uint32_t jobWorkers    = 0;   ///< 0 = jobPoolSize - 1, never below 1
     uint32_t jobMaxAttempts = 5;
     uint32_t staleClaimSec = 300;
+    /// Runs kept per function by the JOB worker's log writes. Should match the
+    /// server's functions.runs_kept, or the two trim one log to two depths.
+    uint32_t functionRunsKept = 50;
     /// How long a single /run or /validate request may occupy a server thread.
     /// Above the wall-time ceiling on purpose: a run that is about to be killed
     /// should report its own timeout rather than have the socket cut first.
@@ -144,6 +163,8 @@ struct RunnerConfig {
             c.jobMaxAttempts = jb.value("max_attempts", c.jobMaxAttempts);
             c.staleClaimSec  = jb.value("stale_claim_sec", c.staleClaimSec);
         }
+        if (j.contains("function_runs_kept"))
+            c.functionRunsKept = j.value("function_runs_kept", c.functionRunsKept);
         if (j.contains("database") && j["database"].is_object())
             c.dbAddress = j["database"].value("address", c.dbAddress);
         if (j.contains("runtime") && j["runtime"].is_object()) {
@@ -239,6 +260,103 @@ private:
 /// The whole adapter is this one translation, which is the point: the protocol
 /// layer never learns that a database exists, and this class holds no logic a
 /// test would want to reach.
+/// The job worker's queue port, over the real queue.
+///
+/// Translates FunctionJob to the worker's JobView and back. The worker never
+/// sees the database, which is what keeps its decisions testable; `raw` carries
+/// the stored row so completing needs no state kept here.
+///
+/// Nothing in here may throw: the worker's contract is that a transient read
+/// reports "nothing to do" rather than killing the loop, because a loop that a
+/// database blip can kill is a loop that stops doing cron.
+class WorkerQueuePort : public svapi::runner::JobQueuePort {
+public:
+    explicit WorkerQueuePort(svapi::FunctionJobQueue& queue) : queue_(queue) {}
+
+    std::optional<svapi::runner::JobView> claimNext(const std::string& runnerId) override {
+        try {
+            std::optional<svapi::FunctionJob> job = queue_.claimNext(runnerId);
+            if (!job) return std::nullopt;
+            svapi::runner::JobView v;
+            v.jobId      = job->jobId;
+            v.project    = job->project;
+            v.functionId = job->functionId;
+            v.trigger    = job->trigger;
+            v.payload    = job->payload;
+            // claimNext increments on claim, so this already counts the attempt
+            // about to happen; 0 would mean the queue did not count it.
+            v.attempts   = job->attempts == 0 ? 1 : job->attempts;
+            v.raw        = job->toJson();
+            v.raw["version"] = job->version;  // toJson does not carry it
+            return v;
+        } catch (const std::exception& e) {
+            spdlog::warn("claim failed: {}", e.what());
+            return std::nullopt;
+        }
+    }
+
+    bool complete(const svapi::runner::JobView& v, bool ok, const std::string& error,
+                  uint32_t retryAfterSec) override {
+        try {
+            svapi::FunctionJob job = svapi::FunctionJob::fromJson(v.raw);
+            job.jobId   = v.jobId;                        // the body never carries `id`
+            job.version = v.raw.value("version", uint64_t{0});
+            return queue_.complete(job, ok, error, retryAfterSec);
+        } catch (const std::exception& e) {
+            spdlog::warn("completing job {} failed: {}", v.jobId, e.what());
+            return false;
+        }
+    }
+
+    uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) override {
+        try {
+            return queue_.reclaimStale(timeoutSec, maxAttempts);
+        } catch (const std::exception& e) {
+            spdlog::warn("reclaim failed: {}", e.what());
+            return 0;
+        }
+    }
+
+private:
+    svapi::FunctionJobQueue& queue_;
+};
+
+/// The job worker's run-log port. ensure() is remembered per project because
+/// the worker is multi-threaded, and a run log write must never change the
+/// outcome of the job it is recording.
+class WorkerRunLogPort : public svapi::runner::RunLogPort {
+public:
+    explicit WorkerRunLogPort(svapi::FunctionRunLogStore& store) : store_(store) {}
+
+    void record(const std::string& project, const svapi::runner::JobRunRecord& entry) override {
+        try {
+            {
+                std::lock_guard<std::mutex> lock(mu_);
+                if (ensured_.insert(project).second) store_.ensure(project);
+            }
+            svapi::FunctionRunLog row;
+            row.runId      = entry.runId;
+            row.functionId = entry.functionId;
+            row.trigger    = entry.trigger;
+            row.ok         = entry.ok;
+            row.status     = entry.status;
+            row.durationMs = entry.durationMs;
+            row.error      = entry.error;
+            row.console    = entry.console;
+            row.headers    = entry.headers;
+            row.startedAt  = entry.startedAt;
+            store_.append(project, row);
+        } catch (const std::exception& e) {
+            spdlog::warn("run log write failed for {}/{}: {}", project, entry.functionId, e.what());
+        }
+    }
+
+private:
+    svapi::FunctionRunLogStore& store_;
+    std::mutex mu_;
+    std::set<std::string> ensured_;
+};
+
 /// ctx.jobs, over the real queue.
 ///
 /// The authorization rule lives HERE rather than in the host context, because
@@ -473,6 +591,26 @@ int main(int argc, char** argv) {
     GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort);
     svapi::runner::RunService service(source, options, &host);
 
+    // THE thing that drains the queue. Without it the scheduler enqueues a job,
+    // nothing ever claims it, and single-flight then correctly refuses to stack
+    // a second copy behind the stuck one - so cron produces exactly zero runs
+    // and looks like a scheduler that never fires. 0.5.0 shipped without this.
+    //
+    // Off unless jobs.enabled, so a runner upgrade never starts draining a
+    // queue in a deployment whose server has no scheduler.
+    svapi::FunctionRunLogStore jobRunLog(db, cfg.functionRunsKept);
+    WorkerQueuePort workerQueue(jobQueue);
+    WorkerRunLogPort workerLog(jobRunLog);
+    std::unique_ptr<svapi::runner::JobWorker> worker;
+    if (cfg.jobsEnabled) {
+        svapi::runner::JobWorkerOptions wo;
+        wo.poolSize    = cfg.jobPoolSize > 0 ? cfg.jobPoolSize : cfg.poolSize;
+        wo.workers     = cfg.jobWorkers;
+        wo.maxAttempts = cfg.jobMaxAttempts;
+        wo.staleClaimSec = cfg.staleClaimSec;
+        worker = std::make_unique<svapi::runner::JobWorker>(service, workerQueue, workerLog, wo);
+    }
+
     // The environment wins over the config file: a secret belongs in
     // runner.env, which systemd can keep at mode 0640, not in a conffile.
     std::string authToken = cfg.authToken;
@@ -540,8 +678,34 @@ int main(int argc, char** argv) {
         reply(res, service.validate(body));
     });
 
-    server.Get("/health", [&service](const httplib::Request&, httplib::Response& res) {
-        reply(res, service.health());
+    server.Get("/health", [&service, &worker, &cfg](const httplib::Request&,
+                                                     httplib::Response& res) {
+        svapi::runner::ProtocolResponse out = service.health();
+        // The job worker's existence is REPORTED, not inferred from an empty
+        // log. 0.5.0 shipped without a worker at all, and the only symptom was
+        // a quiet log that read exactly like an idle one - so cron enqueued and
+        // nothing ran, and a health check that said "ok" was telling the truth
+        // about everything it knew to look at. Anything a deployment can forget
+        // to wire has to be visible here.
+        if (out.body.is_object()) {
+            if (worker) {
+                const svapi::runner::JobWorker::Stats s = worker->stats();
+                out.body["jobs"] = {{"running", true},
+                                    {"workers", cfg.jobWorkers},
+                                    {"claimed", s.claimed},
+                                    {"succeeded", s.succeeded},
+                                    {"retried", s.retried},
+                                    {"failed", s.failed},
+                                    {"complete_failures", s.completeFailures},
+                                    {"reclaimed", s.reclaimed}};
+            } else {
+                // Said plainly, because this state means queued cron and
+                // database events will never run on this runner.
+                out.body["jobs"] = {{"running", false},
+                                    {"reason", "jobs.enabled is false in runner.json"}};
+            }
+        }
+        reply(res, out);
     });
 
     // An unexpected throw must not take the process down: one bad function
@@ -588,9 +752,23 @@ int main(int argc, char** argv) {
                      " ({}s); a job-kind run posted to /run would have its socket cut before"
                      " it could report a timeout", cfg.maxJobWallTimeMs, cfg.readTimeoutSec);
     }
+    // Started after READY so /health answers before any job runs, and a
+    // deployment that is coming up does not begin side-effecting work before it
+    // is reachable.
+    if (worker) {
+        worker->start();
+        spdlog::info("job worker started (lane {}, workers {}, stale claim {}s)", cfg.jobPoolSize,
+                     cfg.jobWorkers, cfg.staleClaimSec);
+    } else {
+        spdlog::info("job worker disabled (jobs.enabled false) - queued cron and database "
+                     "events will NOT run on this runner");
+    }
     sd_notify(0, "READY=1");
     while (g_running) { sd_notify(0, "WATCHDOG=1"); std::this_thread::sleep_for(std::chrono::milliseconds(200)); }
     sd_notify(0, "STOPPING=1");
+    // Stop claiming while the database is still up, and before the service it
+    // runs jobs through goes away. A job in flight runs to completion.
+    if (worker) worker->stop();
     server.stop();
     if (http.joinable()) http.join();
     // Non-zero on a listener failure, so Restart=on-failure actually fires. A

+ 52 - 0
runner/tests/host_context_test.cpp

@@ -65,6 +65,7 @@ std::optional<std::string> base64Decode(std::string_view in);
 std::optional<uint32_t> ttlFrom(const nlohmann::json& payload);
 std::optional<uint64_t> ifVersionFrom(const nlohmann::json& payload);
 nlohmann::json stripDbMetadata(nlohmann::json doc);
+nlohmann::json incrementDeltasFrom(const nlohmann::json& payload);
 uint64_t jobRunAfterSec(const nlohmann::json& payload, int64_t wall_now_ms);
 nlohmann::json jobTrigger(const nlohmann::json& payload, uint32_t depth,
                           const std::string& enqueuedBy, int64_t wall_now_ms);
@@ -417,9 +418,60 @@ TEST(HostDetail, OpVocabularyMatchesTheHttpHandlers) {
     EXPECT_EQ(detail::keyOpForDbOp("delete"), KeyOp::Delete);
     EXPECT_EQ(detail::keyOpForDbOp("search"), KeyOp::Search);
     EXPECT_EQ(detail::keyOpForDbOp("store"), KeyOp::Insert);
+    // An increment writes, so a read-only policy never reaches it, and it is
+    // specifically an update: the document must already exist, and a policy
+    // that may replace one could already set any number to any value.
+    EXPECT_EQ(detail::keyOpForDbOp("increment"), KeyOp::Update);
     EXPECT_FALSE(detail::keyOpForDbOp("drop").has_value());
 }
 
+// `.increment()` deltas: the same rules the HTTP route applies, because they
+// come from the same function - a function author and an HTTP caller must be
+// refused for the same payload.
+TEST(HostDetail, IncrementDeltasAcceptNumbersAndDottedPaths) {
+    nlohmann::json d = detail::incrementDeltasFrom({{"deltas", {{"calls", 1}, {"counts.sent", -2}}}});
+    EXPECT_EQ(d.at("calls"), 1);
+    EXPECT_EQ(d.at("counts.sent"), -2);
+}
+
+// Dropped, not refused: a script that read a document, computed a delta per
+// field and passed the result should not be told off for the `_version` the
+// database itself attached.
+TEST(HostDetail, IncrementDeltasDropIdAndDatabaseMetadata) {
+    nlohmann::json d = detail::incrementDeltasFrom(
+        {{"deltas", {{"calls", 1}, {"id", "x"}, {"_version", 9}}}});
+    EXPECT_EQ(d.size(), 1u);
+    EXPECT_EQ(d.at("calls"), 1);
+}
+
+// No `{"data": ...}` unwrapping on this side: the builder names the argument,
+// so a field actually called `data` stays a field.
+TEST(HostDetail, IncrementDeltasDoNotUnwrapADataKey) {
+    nlohmann::json d = detail::incrementDeltasFrom({{"deltas", {{"data", 3}}}});
+    EXPECT_EQ(d.at("data"), 3);
+}
+
+TEST(HostDetail, IncrementDeltasRefuseWhatCannotBeApplied) {
+    const std::vector<nlohmann::json> bad{
+        nlohmann::json::object(),                                  // no deltas at all
+        {{"deltas", nlohmann::json::object()}},                    // nothing named
+        {{"deltas", {{"calls", "1"}}}},                            // not a number
+        {{"deltas", {{"calls", true}}}},                           // a bool is not 1
+        {{"deltas", {{"calls", nlohmann::json::array({1})}}}},
+        {{"deltas", {{"counts..sent", 1}}}},                       // empty path segment
+        {{"deltas", 5}},                                           // not an object
+    };
+    for (const auto& payload : bad) {
+        bool threw = false;
+        try {
+            detail::incrementDeltasFrom(payload);
+        } catch (const ApiError&) {
+            threw = true;
+        }
+        EXPECT_TRUE(threw) << payload.dump();
+    }
+}
+
 TEST(HostDetail, DenialMessageNamesTheCollectionAndTheOp) {
     const std::string m = detail::deniedMessage("kb_chunks", "list", "scope does not permit");
     EXPECT_NE(m.find("kb_chunks"), std::string::npos) << m;

+ 56 - 0
runner/tests/host_prelude_test.cpp

@@ -515,6 +515,62 @@ TEST(HostPrelude, TheBuilderIsStillImmutable) {
     EXPECT_EQ(out.at("value").at("a"), 1);
 }
 
+// --- Intl's zone data -------------------------------------------------------
+//
+// `Intl.DateTimeFormat` itself is installed by the engine core (see
+// runner/src/intl_shim_js.inc and intl_shim_test.cpp); what the prelude does is
+// hand it the one thing the core has not got, the tz database behind __hostTime.
+
+TEST(HostPrelude, TheIntlBindHookIsUsedAndThenRemoved) {
+    // Leaving a hook that accepts a replacement date source would let user code
+    // reach around the only thing Intl and ctx.time agree on.
+    const nlohmann::json out = runPrelude(
+        "return typeof globalThis.__svapiBindIntlTime;");
+    EXPECT_EQ(out.at("value"), "undefined");
+}
+
+TEST(HostPrelude, IntlReachesTheSameHostTimeBindingCtxTimeDoes) {
+    const nlohmann::json out = runPrelude(
+        "const s = new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest',"
+        "    year: 'numeric', month: 'numeric', day: 'numeric' }).format(1800000000000);"
+        "return s;");
+    EXPECT_EQ(out.at("value"), "10/7/2026")
+        << "the formatter must render the civil fields the host returned";
+    ASSERT_EQ(out.at("calls").size(), 1u) << out.at("calls").dump();
+    const nlohmann::json& call = out.at("calls").at(0);
+    EXPECT_EQ(call.at("kind"), "time");
+    EXPECT_EQ(call.at("args").at(0), "parts")
+        << "the shim asks for civil fields and does no date maths of its own";
+    EXPECT_EQ(call.at("args").at(1).at("zone"), "Europe/Budapest");
+    EXPECT_EQ(call.at("args").at(1).at("epochMs"), 1800000000000LL);
+}
+
+TEST(HostPrelude, AUtcFormatterDoesNotTouchTheHostAtAll) {
+    // Date's own getUTC* accessors already answer UTC, which is what lets a
+    // module format a UTC timestamp before any host binding exists.
+    const nlohmann::json out = runPrelude(
+        "return new Intl.DateTimeFormat('en').format(0);");
+    EXPECT_EQ(out.at("value"), "1/1/1970");
+    EXPECT_EQ(out.at("calls").size(), 0u) << out.at("calls").dump();
+}
+
+TEST(HostPrelude, CtxTimeIsUnaffectedByTheIntlShim) {
+    // ctx.time is the supported surface and must behave exactly as it did: same
+    // op names, same payload, same validation.
+    const nlohmann::json args = onlyCall(
+        runPrelude("new Intl.DateTimeFormat('en');"
+                   "return ctx.time.format(0, 'Europe/Budapest', 'YYYY. MMMM D.', 'hu');"),
+        "time");
+    EXPECT_EQ(args.at(0), "format");
+    EXPECT_EQ(args.at(1).at("pattern"), "YYYY. MMMM D.");
+    EXPECT_EQ(args.at(1).at("locale"), "hu");
+    // And its refusals are still refusals: an unknown locale is the native
+    // side's call, an empty pattern is still caught before the host.
+    expectRefused("new Intl.DateTimeFormat('fr');"
+                  "return ctx.time.format(0, 'Europe/Budapest', '');",
+                  "validation");
+}
+
 TEST(HostPrelude, LogStillFormatsObjectsAsJson) {
     const nlohmann::json out = runPrelude("ctx.log('two', 2, { a: 1 }); return null;");
     ASSERT_EQ(out.at("calls").size(), 1u);

+ 494 - 0
runner/tests/intl_shim_test.cpp

@@ -0,0 +1,494 @@
+// Tests for runner/src/intl_shim_js.inc - the minimal `Intl.DateTimeFormat`
+// the engine core installs into every context.
+//
+// WHY a file of its own rather than more cases in host_prelude_test.cpp: the
+// prelude test stands fake recorders in for the host bindings, which is exactly
+// right for "was the argument checked before the host was reached" and exactly
+// wrong here. What has to be asserted about a date formatter is that it prints
+// the right local time, and the only thing that knows that is the tz database.
+//
+// So this file links functions/timezone.cpp (pure, no database client) and
+// builds the shim's zone backend out of REAL `zonePartsAt` answers, injected as
+// a lookup table. The Budapest instants below straddle both DST transitions, so
+// a wrong offset cannot pass.
+//
+// The other half of the point is the LOAD-TIME path: five of six real functions
+// failed to register because they built a formatter at module scope and
+// quickjs-ng has no Intl. That is asserted through readExport(), which is the
+// call registration actually makes, and which installs no host bindings at all.
+#include <gtest/gtest.h>
+
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "functions/timezone.hpp"
+#include "runner/js_runtime.hpp"
+
+using svapi::runner::JsBytecode;
+using svapi::runner::JsResult;
+using svapi::runner::JsRuntime;
+
+namespace {
+
+// 2026-01-15 12:00:00Z -> 13:00 CET in Budapest, a Thursday.
+constexpr int64_t kWinter = 1768478400000LL;
+// 2026-07-15 12:00:00Z -> 14:00 CEST, a Wednesday.
+constexpr int64_t kSummer = 1784116800000LL;
+// The spring-forward minute: 00:59Z is 01:59 CET, 01:00Z is already 03:00 CEST.
+constexpr int64_t kBeforeSpringForward = 1774745940000LL;
+constexpr int64_t kAfterSpringForward = 1774746000000LL;
+// The repeated hour in autumn: both of these are 02:30 local, one CEST, one CET.
+constexpr int64_t kFirstRepeatedHalfTwo = 1792888200000LL;
+constexpr int64_t kSecondRepeatedHalfTwo = 1792891800000LL;
+
+const char* const kZone = "Europe/Budapest";
+
+/// The shim asks the host exactly one question - `parts(epochMs, zone)` - so a
+/// table of real answers is a complete backend. Built from the tz database, not
+/// from constants, so the test cannot drift from what a cron schedule or
+/// ctx.time would compute for the same instant.
+std::string partsTableJs() {
+    const std::pair<int64_t, const char*> wanted[] = {
+        {kWinter, kZone},                 {kSummer, kZone},
+        {kBeforeSpringForward, kZone},    {kAfterSpringForward, kZone},
+        {kFirstRepeatedHalfTwo, kZone},   {kSecondRepeatedHalfTwo, kZone},
+        {kWinter, "America/New_York"},
+    };
+    nlohmann::json table = nlohmann::json::object();
+    for (const auto& [ms, zone] : wanted) {
+        auto p = svapi::functions::zonePartsAt(zone, static_cast<std::time_t>(ms / 1000));
+        if (!p) continue;  // no tzdata for this zone on this host; the case skips below
+        table[std::to_string(ms) + "@" + zone] = nlohmann::json{
+            {"year", p->year},         {"month", p->month},   {"day", p->day},
+            {"hour", p->hour},         {"minute", p->minute}, {"second", p->second},
+            {"weekday", p->weekday},   {"offsetSec", p->offsetSec},
+            {"dst", p->dst},           {"abbrev", p->abbrev}};
+    }
+    return table.dump();
+}
+
+/// Install the real zone backend through the shim's own hook, then run `body`.
+/// `run()` is called with no host bindings, so the hook is still in place -
+/// which is also how a module behaves while its descriptor is read.
+const char* kHarness = R"JS(
+const __parts = %TABLE%;
+
+export default function () {
+  globalThis.__svapiBindIntlTime(function (op, payload) {
+    if (op !== 'parts') throw new Error('the shim asked for an unexpected op: ' + op);
+    const key = String(payload.epochMs) + '@' + payload.zone;
+    const p = __parts[key];
+    if (p === undefined) throw new Error('no recorded parts for ' + key);
+    return p;
+  });
+
+  let value = null;
+  let threw = null;
+  try {
+    value = (function () { %BODY% })();
+  } catch (e) {
+    threw = { name: e.name, code: e.code === undefined ? null : e.code,
+              message: String(e.message) };
+  }
+  return { value: value === undefined ? null : value, threw: threw };
+}
+)JS";
+
+void substitute(std::string& src, const std::string& token, const std::string& with) {
+    src.replace(src.find(token), token.size(), with);
+}
+
+nlohmann::json runIntl(const std::string& body) {
+    static const std::string table = partsTableJs();
+    std::string src = kHarness;
+    substitute(src, "%TABLE%", table);
+    substitute(src, "%BODY%", body);
+
+    JsRuntime rt;
+    std::string error;
+    auto bc = rt.compile(src, "intl_shim_test.js", error);
+    EXPECT_TRUE(bc.has_value()) << "compile failed: " << error;
+    if (!bc) return nlohmann::json::object();
+    JsResult result = rt.run(*bc, nlohmann::json::object(), 0, nullptr);
+    EXPECT_TRUE(result.ok) << result.error;
+    return result.value;
+}
+
+/// The value of an expression that was expected to succeed.
+nlohmann::json value(const std::string& body) {
+    const nlohmann::json out = runIntl(body);
+    EXPECT_TRUE(out.contains("threw") && out.at("threw").is_null())
+        << body << " threw: " << out.dump();
+    return out.at("value");
+}
+
+bool haveBudapest() {
+    return svapi::functions::zonePartsAt(kZone, static_cast<std::time_t>(kWinter / 1000))
+        .has_value();
+}
+
+} // namespace
+
+// --- it exists, and it is shaped like the real one --------------------------
+
+TEST(IntlShim, IntlAndDateTimeFormatAreGlobalButNumberFormatIsAbsent) {
+    const nlohmann::json v = value(
+        "return { intl: typeof Intl, dtf: typeof Intl.DateTimeFormat,"
+        "         number: typeof Intl.NumberFormat, plural: typeof Intl.PluralRules,"
+        "         supported: typeof Intl.supportedValuesOf,"
+        "         supportedLocalesOf: typeof Intl.DateTimeFormat.supportedLocalesOf };");
+    EXPECT_EQ(v.at("intl"), "object");
+    EXPECT_EQ(v.at("dtf"), "function");
+    EXPECT_EQ(v.at("supportedLocalesOf"), "function");
+    // ABSENT rather than present-and-throwing, so `typeof Intl.NumberFormat ===
+    // 'undefined'` works as a feature test and a polyfill can install its own.
+    EXPECT_EQ(v.at("number"), "undefined");
+    EXPECT_EQ(v.at("plural"), "undefined");
+    EXPECT_EQ(v.at("supported"), "undefined");
+}
+
+TEST(IntlShim, ConstructsWithAndWithoutNew) {
+    // The real Intl.DateTimeFormat is callable both ways, and real code uses
+    // both. A shim that only works with `new` breaks half of it.
+    const nlohmann::json v = value(
+        "const a = new Intl.DateTimeFormat('en');"
+        "const b = Intl.DateTimeFormat('en');"
+        "return { a: typeof a.format, b: typeof b.format,"
+        "         instance: b instanceof Intl.DateTimeFormat,"
+        "         same: a.format(0) === b.format(0) };");
+    EXPECT_EQ(v.at("a"), "function");
+    EXPECT_EQ(v.at("b"), "function");
+    EXPECT_EQ(v.at("instance"), true);
+    EXPECT_EQ(v.at("same"), true);
+}
+
+TEST(IntlShim, FormatSurvivesBeingDetachedFromItsFormatter) {
+    // `dates.map(fmt.format)` is ordinary code; the real API's format is a
+    // bound function, so it must not need its receiver.
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en').format;"
+        "return [0, 86400000].map(f);");
+    ASSERT_TRUE(v.is_array());
+    EXPECT_EQ(v.at(0), "1/1/1970");
+    EXPECT_EQ(v.at(1), "1/2/1970");
+}
+
+// --- locales ----------------------------------------------------------------
+
+TEST(IntlShim, ALocaleArrayTakesTheFirstSupportedEntry) {
+    const nlohmann::json v = value(
+        "return { picked: new Intl.DateTimeFormat(['fr-FR', 'hu-HU', 'en'])"
+        "                   .resolvedOptions().locale,"
+        "         none: new Intl.DateTimeFormat(['fr', 'de-AT']).resolvedOptions().locale,"
+        "         regional: new Intl.DateTimeFormat('hu-HU').resolvedOptions().locale,"
+        "         undef: new Intl.DateTimeFormat().resolvedOptions().locale };");
+    EXPECT_EQ(v.at("picked"), "hu");
+    // An unsupported locale RESOLVES to the default. Throwing is what the real
+    // API does for a malformed tag, not for one it cannot match - and throwing
+    // at module load is the failure this shim exists to remove.
+    EXPECT_EQ(v.at("none"), "en");
+    // Only the language subtag is honoured, so the resolved tag is the base
+    // language: reporting 'hu-HU' would promise regional data there is none of.
+    EXPECT_EQ(v.at("regional"), "hu");
+    EXPECT_EQ(v.at("undef"), "en");
+}
+
+TEST(IntlShim, AnUnsupportedLocaleStillFormatsInsteadOfThrowing) {
+    const nlohmann::json out = runIntl(
+        "return new Intl.DateTimeFormat('ja-JP', { year: 'numeric', month: 'long',"
+        "                                          day: 'numeric' }).format(0);");
+    ASSERT_TRUE(out.at("threw").is_null()) << out.dump();
+    EXPECT_EQ(out.at("value"), "January 1, 1970");
+}
+
+TEST(IntlShim, SupportedLocalesOfReportsOnlyWhatTheNamesCover) {
+    const nlohmann::json v = value(
+        "return Intl.DateTimeFormat.supportedLocalesOf(['fr', 'hu-HU', 'en-GB', 'hu']);");
+    EXPECT_EQ(v, nlohmann::json({"hu", "en"}));
+}
+
+// --- real zones, real DST ---------------------------------------------------
+
+TEST(IntlShim, FormatsABudapestInstantInWinterAndInSummer) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest',"
+        "    year: 'numeric', month: 'short', day: 'numeric',"
+        "    hour: 'numeric', minute: '2-digit' });"
+        "return { winter: f.format(1768478400000), summer: f.format(1784116800000) };");
+    // The same UTC wall clock, an hour apart in local time: that hour IS the
+    // offset change, and it is the whole reason this shim may not guess.
+    EXPECT_EQ(v.at("winter"), "Jan 15, 2026, 1:00 PM");
+    EXPECT_EQ(v.at("summer"), "Jul 15, 2026, 2:00 PM");
+}
+
+TEST(IntlShim, SpringForwardSkipsAnHourWithinOneMinuteOfUtc) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest',"
+        "    hour: '2-digit', minute: '2-digit', hour12: false, timeZoneName: 'short' });"
+        "return { before: f.format(1774745940000), after: f.format(1774746000000) };");
+    EXPECT_EQ(v.at("before"), "01:59 CET");
+    EXPECT_EQ(v.at("after"), "03:00 CEST");
+}
+
+TEST(IntlShim, TheRepeatedAutumnHourPrintsTwiceWithDifferentZoneNames) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest',"
+        "    hour: '2-digit', minute: '2-digit', hour12: false, timeZoneName: 'short' });"
+        "return { first: f.format(1792888200000), second: f.format(1792891800000) };");
+    // Two different instants, one hour apart, both 02:30 local. Only the zone
+    // name tells them apart, which is why timeZoneName is worth having.
+    EXPECT_EQ(v.at("first"), "02:30 CEST");
+    EXPECT_EQ(v.at("second"), "02:30 CET");
+}
+
+TEST(IntlShim, HungarianUsesHungarianFieldOrderAndNames) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "const long_ = new Intl.DateTimeFormat('hu', { timeZone: 'Europe/Budapest',"
+        "    year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });"
+        "const numeric = new Intl.DateTimeFormat('hu-HU', { timeZone: 'Europe/Budapest',"
+        "    year: 'numeric', month: '2-digit', day: '2-digit',"
+        "    hour: '2-digit', minute: '2-digit' });"
+        "return { long_: long_.format(1768478400000), numeric: numeric.format(1768478400000) };");
+    // The weekday goes last in Hungarian and the month name is lowercase.
+    EXPECT_EQ(v.at("long_"), "2026. január 15., csütörtök");
+    // 24-hour by default for hu, because 1 PM is not how a Hungarian clock
+    // reads.
+    EXPECT_EQ(v.at("numeric"), "2026. 01. 15. 13:00");
+}
+
+TEST(IntlShim, Hour12IsHonouredExplicitlyInBothDirections) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "function at(opts) {"
+        "  return new Intl.DateTimeFormat('en',"
+        "      Object.assign({ timeZone: 'Europe/Budapest', hour: 'numeric',"
+        "                      minute: '2-digit' }, opts)).format(1768478400000);"
+        "}"
+        "return { dflt: at({}), off: at({ hour12: false }), on: at({ hour12: true }),"
+        "         cycle23: at({ hourCycle: 'h23' }),"
+        "         hu: new Intl.DateTimeFormat('hu', { timeZone: 'Europe/Budapest',"
+        "               hour: 'numeric', minute: '2-digit', hour12: true })"
+        "               .format(1768478400000) };");
+    EXPECT_EQ(v.at("dflt"), "1:00 PM");
+    EXPECT_EQ(v.at("off"), "13:00");
+    EXPECT_EQ(v.at("on"), "1:00 PM");
+    EXPECT_EQ(v.at("cycle23"), "13:00");
+    // Hungarian's day period, and after the time rather than before it.
+    EXPECT_EQ(v.at("hu"), "1:00 du.");
+}
+
+TEST(IntlShim, MidnightIsTwelveAmNotZeroAm) {
+    // The classic off-by-twelve. 1970-01-01T00:00:00Z is midnight UTC.
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en', { hour: 'numeric', minute: '2-digit' });"
+        "return { midnight: f.format(0), noon: f.format(12 * 3600 * 1000) };");
+    EXPECT_EQ(v.at("midnight"), "12:00 AM");
+    EXPECT_EQ(v.at("noon"), "12:00 PM");
+}
+
+// --- formatToParts ----------------------------------------------------------
+
+TEST(IntlShim, FormatToPartsIsTheSameRenderingSplitUp) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest',"
+        "    weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',"
+        "    hour: 'numeric', minute: '2-digit' });"
+        "const parts = f.formatToParts(1768478400000);"
+        "return { parts: parts, joined: parts.map(function (p) { return p.value; }).join(''),"
+        "         formatted: f.format(1768478400000) };");
+    EXPECT_EQ(v.at("joined"), v.at("formatted"))
+        << "format() must be exactly the concatenation of formatToParts()";
+    EXPECT_EQ(v.at("formatted"), "Thursday, January 15, 2026, 1:00 PM");
+
+    const nlohmann::json expected = nlohmann::json::array({
+        {{"type", "weekday"}, {"value", "Thursday"}},
+        {{"type", "literal"}, {"value", ", "}},
+        {{"type", "month"}, {"value", "January"}},
+        {{"type", "literal"}, {"value", " "}},
+        {{"type", "day"}, {"value", "15"}},
+        {{"type", "literal"}, {"value", ", "}},
+        {{"type", "year"}, {"value", "2026"}},
+        {{"type", "literal"}, {"value", ", "}},
+        {{"type", "hour"}, {"value", "1"}},
+        {{"type", "literal"}, {"value", ":"}},
+        {{"type", "minute"}, {"value", "00"}},
+        {{"type", "literal"}, {"value", " "}},
+        {{"type", "dayPeriod"}, {"value", "PM"}},
+    });
+    EXPECT_EQ(v.at("parts"), expected);
+}
+
+// --- resolvedOptions --------------------------------------------------------
+
+TEST(IntlShim, ResolvedOptionsReportsTheZoneThatWasActuallyUsed) {
+    const nlohmann::json v = value(
+        "return { given: new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest' })"
+        "                  .resolvedOptions(),"
+        "         dflt: new Intl.DateTimeFormat('en').resolvedOptions(),"
+        "         gmt: new Intl.DateTimeFormat('en', { timeZone: 'gmt' })"
+        "                  .resolvedOptions().timeZone,"
+        "         withHour: new Intl.DateTimeFormat('hu', { hour: 'numeric' })"
+        "                  .resolvedOptions() };");
+    EXPECT_EQ(v.at("given").at("timeZone"), "Europe/Budapest");
+    EXPECT_EQ(v.at("given").at("calendar"), "gregory");
+    // No system zone is reachable from this engine, so the default is UTC and
+    // says so rather than pretending to be the host's local zone.
+    EXPECT_EQ(v.at("dflt").at("timeZone"), "UTC");
+    EXPECT_EQ(v.at("gmt"), "UTC");
+    // The real API reports the default date components when none were asked for.
+    EXPECT_EQ(v.at("dflt").at("year"), "numeric");
+    EXPECT_EQ(v.at("dflt").at("month"), "numeric");
+    EXPECT_EQ(v.at("dflt").at("day"), "numeric");
+    // hour12/hourCycle only when an hour is being rendered, as in the real API.
+    EXPECT_FALSE(v.at("dflt").contains("hour12"));
+    EXPECT_EQ(v.at("withHour").at("hour12"), false);
+    EXPECT_EQ(v.at("withHour").at("hourCycle"), "h23");
+}
+
+// --- argument handling ------------------------------------------------------
+
+TEST(IntlShim, FormatAcceptsADateANumberOrNothing) {
+    const nlohmann::json v = value(
+        "const f = new Intl.DateTimeFormat('en');"
+        "return { date: f.format(new Date(0)), number: f.format(0),"
+        "         now: typeof f.format(), invalid: (function () {"
+        "           try { f.format(new Date('nonsense')); return 'no throw'; }"
+        "           catch (e) { return e.name; } })() };");
+    EXPECT_EQ(v.at("date"), "1/1/1970");
+    EXPECT_EQ(v.at("number"), "1/1/1970");
+    EXPECT_EQ(v.at("now"), "string");
+    EXPECT_EQ(v.at("invalid"), "RangeError");
+}
+
+TEST(IntlShim, AnOptionValueOutsideTheEnumerationIsARangeError) {
+    // The real API throws for this, and it is a typo in a literal rather than
+    // data: being lenient would print "1" where the author wrote "01".
+    const nlohmann::json out = runIntl(
+        "return new Intl.DateTimeFormat('en', { month: '2digit' }).format(0);");
+    ASSERT_FALSE(out.at("threw").is_null());
+    EXPECT_EQ(out.at("threw").at("name"), "RangeError");
+}
+
+TEST(IntlShim, AnUnknownZoneIsRefusedByTheHostNotGuessedAt) {
+    // The zone is NOT validated at construction: the host is the only thing
+    // that can judge a zone name, and a formatter is often built where the host
+    // is out of reach. It surfaces at format() instead - never as a silent
+    // fallback to UTC, which would move somebody's report by an hour.
+    const nlohmann::json out = runIntl(
+        "const f = new Intl.DateTimeFormat('en', { timeZone: 'Mars/Olympus' });"
+        "return f.format(1768478400000);");
+    ASSERT_FALSE(out.at("threw").is_null()) << out.dump();
+}
+
+// --- Date.prototype.toLocale* ----------------------------------------------
+
+TEST(IntlShim, DateToLocaleMethodsGoThroughTheSameFormatter) {
+    if (!haveBudapest()) GTEST_SKIP() << "no tzdata for " << kZone;
+    const nlohmann::json v = value(
+        "const d = new Date(1768478400000);"
+        "const z = { timeZone: 'Europe/Budapest' };"
+        "return { date: d.toLocaleDateString('en', z),"
+        "         time: d.toLocaleTimeString('en', z),"
+        "         both: d.toLocaleString('hu', z),"
+        "         narrowed: d.toLocaleTimeString('en', { timeZone: 'Europe/Budapest',"
+        "                                                hour: '2-digit', hour12: false }),"
+        "         invalid: new Date('nonsense').toLocaleDateString('en') };");
+    EXPECT_EQ(v.at("date"), "1/15/2026");
+    EXPECT_EQ(v.at("time"), "1:00:00 PM");
+    EXPECT_EQ(v.at("both"), "2026. 01. 15. 13:00:00");
+    // Asking for an hour drops the default minutes and seconds, as the real API
+    // does: otherwise {hour:'2-digit'} would still print a full clock time.
+    EXPECT_EQ(v.at("narrowed"), "13");
+    EXPECT_EQ(v.at("invalid"), "Invalid Date");
+}
+
+TEST(IntlShim, AToLocaleCallThatTheShimCannotServeFallsBackToTheEngine) {
+    // The fallback is what keeps this change from breaking a function that
+    // already registers and already calls toLocaleDateString(): an unknown zone
+    // returns the engine's own answer rather than throwing.
+    const nlohmann::json out = runIntl(
+        "return typeof new Date(0).toLocaleDateString('en', { timeZone: 'Mars/Olympus' });");
+    ASSERT_TRUE(out.at("threw").is_null()) << out.dump();
+    EXPECT_EQ(out.at("value"), "string");
+}
+
+// --- the load-time path, which is the whole point ---------------------------
+
+namespace {
+
+/// Compile a module and read one export, exactly as registration does: no host
+/// bindings, so a formatter built at module scope has no zone data behind it.
+nlohmann::json readExportOf(const std::string& source, const std::string& name,
+                            std::string& error) {
+    JsRuntime rt;
+    auto bc = rt.compile(source, "intl_load_time.js", error);
+    if (!bc) return nlohmann::json();
+    auto out = rt.readExport(*bc, name, error);
+    return out.value_or(nlohmann::json());
+}
+
+} // namespace
+
+TEST(IntlShim, AModuleThatBuildsAFormatterAtLoadTimeCanBeRegistered) {
+    // This is the bug. Five of six real functions did exactly this and failed
+    // to register with compile_failed, because `Intl` did not exist.
+    const std::string source =
+        "const FMT = new Intl.DateTimeFormat('hu-HU', {\n"
+        "  timeZone: 'Europe/Budapest', year: 'numeric', month: '2-digit', day: '2-digit',\n"
+        "  hour: '2-digit', minute: '2-digit'\n"
+        "});\n"
+        "export const on = { function_id: 'report', http: { method: 'GET', path: '/r' } };\n"
+        "export default function (ctx) { return { at: FMT.format(Date.now()) }; }\n";
+    std::string error;
+    const nlohmann::json on = readExportOf(source, "on", error);
+    ASSERT_TRUE(error.empty()) << error;
+    EXPECT_EQ(on.at("function_id"), "report");
+}
+
+TEST(IntlShim, AUtcFormatterEvenFormatsAtLoadTime) {
+    // UTC needs no zone database, so the shim answers it on its own. That is
+    // what makes a module which stamps a build time at load time registrable.
+    const std::string source =
+        "const FMT = new Intl.DateTimeFormat('en', { timeZone: 'UTC',\n"
+        "  year: 'numeric', month: '2-digit', day: '2-digit' });\n"
+        "export const on = { stamp: FMT.format(1768478400000) };\n"
+        "export default function () { return null; }\n";
+    std::string error;
+    const nlohmann::json on = readExportOf(source, "on", error);
+    ASSERT_TRUE(error.empty()) << error;
+    EXPECT_EQ(on.at("stamp"), "01/15/2026");
+}
+
+TEST(IntlShim, FormattingANonUtcZoneAtLoadTimeSaysWhyItCannot) {
+    // Constructing is fine; formatting is not, because the tz database is
+    // reached through the host and there is no host while a descriptor is read.
+    // The message has to say that, or the author's next move is to file a bug
+    // about a formatter that works in the handler and not above it.
+    const std::string source =
+        "const FMT = new Intl.DateTimeFormat('en', { timeZone: 'Europe/Budapest' });\n"
+        "export const on = { stamp: FMT.format(0) };\n"
+        "export default function () { return null; }\n";
+    std::string error;
+    readExportOf(source, "on", error);
+    ASSERT_FALSE(error.empty());
+    EXPECT_NE(error.find("while a module is being loaded"), std::string::npos) << error;
+}
+
+TEST(IntlShim, AModuleCallingToLocaleDateStringAtLoadTimeStillRegisters) {
+    // The regression that mattered most: these methods already worked (via the
+    // engine's own implementation), so routing them through the shim may not
+    // make a module that was registering stop.
+    const std::string source =
+        "export const on = { stamp: typeof new Date(0).toLocaleDateString() };\n"
+        "export default function () { return null; }\n";
+    std::string error;
+    const nlohmann::json on = readExportOf(source, "on", error);
+    ASSERT_TRUE(error.empty()) << error;
+    EXPECT_EQ(on.at("stamp"), "string");
+}

+ 58 - 0
src/documents_util.hpp

@@ -2,6 +2,7 @@
 #include "errors.hpp"
 #include <nlohmann/json.hpp>
 #include <cerrno>
+#include <cmath>
 #include <cstdint>
 #include <cstdlib>
 #include <optional>
@@ -120,4 +121,61 @@ inline nlohmann::json documentBody(const nlohmann::json& body) {
     return doc;
 }
 
+/// The increment deltas, checked: field -> number, where a dotted key addresses
+/// a nested field.
+///
+/// Validated strictly because the database applies the whole set or nothing: a
+/// non-number anywhere in the map refuses the entire call, so catching it here
+/// turns an all-or-nothing surprise into a named field. Shared by the HTTP route
+/// and the `ctx.collections(...).increment()` binding so a function and an HTTP
+/// caller are told the same thing about the same payload.
+///
+/// A non-finite double is refused for the same reason the database refuses
+/// integer overflow: a counter that has become NaN cannot be compared, summed
+/// or recovered, and nothing downstream would ever tell the caller when it
+/// happened.
+inline nlohmann::json validateIncrementDeltas(nlohmann::json deltas) {
+    if (!deltas.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "the body must be an object of field -> number");
+    // Empty is refused rather than treated as a no-op: an increment of nothing
+    // is a caller that built its payload wrong, and answering 200 with the
+    // document's unchanged values would hide it. It is also where a body naming
+    // only `id` or the database's own `_version` lands, neither of which is an
+    // incrementable field.
+    if (deltas.empty())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "name at least one field to increment, as field -> number");
+    for (auto it = deltas.begin(); it != deltas.end(); ++it) {
+        // is_number() is false for booleans in nlohmann, which is what we want:
+        // `true` is not 1 here.
+        if (!it->is_number())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "the increment for '" + it.key() + "' must be a number");
+        if (it->is_number_float() && !std::isfinite(it->get<double>()))
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "the increment for '" + it.key() + "' must be a finite number");
+        if (it.key().empty())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "a field name must not be empty");
+        // A dotted key is a path into the document, so an empty segment
+        // addresses nothing - see validateIndexFieldPath() for the same rule on
+        // the index routes.
+        if (it.key().front() == '.' || it.key().back() == '.' ||
+            it.key().find("..") != std::string::npos)
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "the field path '" + it.key() + "' has an empty segment");
+    }
+    return deltas;
+}
+
+/// The deltas carried by an atomic-increment HTTP body.
+///
+/// Read through documentBody() so a caller that wraps every body it sends does
+/// not have to stop wrapping for this one route, and so `data` beside siblings
+/// is the same 422 here as on a write.
+inline nlohmann::json incrementDeltas(const nlohmann::json& body) {
+    return validateIncrementDeltas(documentBody(body));
+}
+
 } // namespace svapi

+ 25 - 4
src/handlers/collections.cpp

@@ -5,6 +5,26 @@
 #include <algorithm>
 #include <cctype>
 namespace svapi {
+namespace {
+
+// Drop a collection AND the index declarations attached to its name.
+//
+// dropCollection() removes the documents and the collection's metadata but
+// leaves its declared indexes behind, including unique ones. A later collection
+// created under the same name therefore inherits constraints nobody asked for:
+// a write that should succeed is refused as a duplicate, and a unique index the
+// new owner declares reports already_existed instead of validating their data.
+// Undeclaring first is the only way to make a name reusable.
+void dropCollectionAndIndexes(DbGateway& db, const std::string& qc) {
+    for (const auto& idx : db.client().listIndexes(qc))
+        db.client().dropIndex(qc, idx.field);
+    for (const auto& fields : db.client().listCompositeUniqueIndexes(qc))
+        db.client().dropCompositeUniqueIndex(qc, fields);
+    db.client().dropCollection(qc);
+}
+
+} // namespace
+
 void registerCollectionRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
@@ -27,9 +47,10 @@ void registerCollectionRoutes(ApiServer& s) {
         }
         if (d->registry.get(project, name)) throw ApiError(ErrCode::Unprocessable, "exists", "collection already exists");
         // Drop any stale DB-layer collection (e.g. left from a prior dropProject that didn't
-        // fully clean up its data — DB v2.3.1 Stage F caveat).
+        // fully clean up its data - DB v2.3.1 Stage F caveat), indexes included,
+        // so the new collection starts with no inherited constraints.
         if (d->db.client().getCollectionInfo(qualify(project, name)))
-            d->db.client().dropCollection(qualify(project, name));
+            dropCollectionAndIndexes(d->db, qualify(project, name));
         if (!d->db.client().createCollection(qualify(project, name), 0, false, 0, dim))
             throw ApiError(ErrCode::Unavailable, "db_error", "failed to create collection");
         d->registry.add(project, {name, kind, dim, model, 0});
@@ -110,7 +131,7 @@ void registerCollectionRoutes(ApiServer& s) {
         if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
         const std::string qc = qualify(project, name);
         // dropCollection() clears the collection's metadata but does NOT purge the
-        // underlying (vector) index — orphan rows survive and leak into a later
+        // underlying (vector) index - orphan rows survive and leak into a later
         // same-name collection (search returns them even though document_count is 0).
         // remove() per id DOES purge the index, so delete every document first, then
         // drop the now-empty collection. (See docs/bugs/2026-06-02-collection-delete-leaks-vectors.md)
@@ -121,7 +142,7 @@ void registerCollectionRoutes(ApiServer& s) {
             if (id.empty()) id = doc.value("id", std::string());
             if (!id.empty()) d->db.client().remove(qc, id);
         }
-        d->db.client().dropCollection(qc);
+        dropCollectionAndIndexes(d->db, qc);
         d->registry.remove(project, name);
         sendJson(res, 200, {{"deleted", name}});
     });

+ 42 - 0
src/handlers/documents.cpp

@@ -278,6 +278,48 @@ void registerDocumentRoutes(ApiServer& s) {
         }
     });
 
+    // Atomic counters: one locked server-side read-modify-write per call, so
+    // concurrent increments cannot lose each other the way a read, add and
+    // write-back does however carefully it is version-checked.
+    //
+    // POST on a sub-resource rather than a flag on PATCH, because a PATCH body
+    // and an increment body look identical and mean opposite things: {"calls":1}
+    // is "set calls to 1" on PATCH and "add 1 to calls" here. One body shape
+    // with two meanings decided by a query parameter is the kind of API where a
+    // forgotten parameter silently resets a counter to 1. It is also not
+    // idempotent, which POST is allowed to be and PUT is not.
+    //
+    // KeyOp::Update: it is a write, so a scope granting only `read` never
+    // reaches it, and it is specifically an update - the database requires the
+    // document to exist and this route creates nothing. Not a new KeyOp of its
+    // own: a key that may replace a document may already set any number to any
+    // value, so increment grants no power `update` did not, and inventing an op
+    // would silently strip the ability from every scope already granting it.
+    svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+)/increment)",
+             [d](const httplib::Request& req, httplib::Response& res) {
+        Target t = scoped(d, req, 1, 2, KeyOp::Update);
+        const std::string id = req.matches[3];
+        nlohmann::json deltas = incrementDeltas(bodyJson(req));
+
+        smartbotic::database::Client::FailureDetail detail;
+        auto values = d->db.client().increment(t.qualified, id, deltas, detail);
+        // 404 on a missing document, deliberately not an implicit create: the
+        // starting document is the caller's to describe, and a counter conjured
+        // from a typo'd id is a counter nobody ever reads. The idiom is
+        // increment, then on 404 POST the document at a fixed id, then on 409
+        // increment again - which is safe because that POST is the only thing
+        // that can create it.
+        //
+        // Everything else keeps the database's own classification: a field
+        // holding a non-number is InvalidArgument and so 422, integer overflow
+        // likewise, and nothing at all was applied in either case.
+        if (!values) throw apiErrorFor(detail, "no such document");
+        // The new values are the entire point of the call, so 200 with a body
+        // rather than 204: a caller that has to re-read to learn what its
+        // increment produced has lost the atomicity it came here for.
+        sendJson(res, 200, {{"id", id}, {"values", *values}});
+    });
+
     svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         Target t = scoped(d, req, 1, 2, KeyOp::Delete);
         std::string id = req.matches[3];

+ 117 - 21
src/handlers/indexes.cpp

@@ -1,46 +1,83 @@
 #include <cstdlib>
 
+#include "db_errors.hpp"
 #include "errors.hpp"
+#include "index_request.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
 
 namespace svapi {
+namespace {
+
+/// The refusal for a declaration the database would not accept.
+///
+/// Shared by the single-field and the composite call so both answer 409
+/// `duplicate_values` with the colliding ids, rather than one of them being
+/// the generic 503 - a caller that must now de-duplicate its data needs the
+/// examples whichever form it used.
+ApiError indexDeclineError(const smartbotic::database::Client::CreateIndexResult& r,
+                           const std::string& what) {
+    if (!r.duplicateExamples.empty()) {
+        nlohmann::json ex = nlohmann::json::array();
+        for (const auto& id : r.duplicateExamples) ex.push_back(id);
+        return ApiError(ErrCode::Conflict, "duplicate_values",
+                        what + " already holds duplicate values",
+                        {{"duplicate_examples", ex}});
+    }
+    return ApiError(ErrCode::Unavailable, "db_error",
+                    r.error.empty() ? "failed to create index" : r.error);
+}
+
+/// A composite constraint as the response reports it.
+nlohmann::json compositeJson(const std::vector<std::string>& fields) {
+    // `unique` is stated rather than implied: a UI or a client walking both
+    // halves of GET /indexes can then read one key on every entry, and the
+    // field is the honest answer anyway - a composite is never non-unique.
+    return nlohmann::json{{"fields", fields}, {"unique", true}};
+}
+
+} // namespace
 
 void registerIndexRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
     // Declare an index. Backfills existing rows, so it is usable immediately.
     // Idempotent: re-declaring an existing index reports already_existed.
+    //
+    // `fields` declares a COMPOSITE unique constraint on the same route rather
+    // than on one of its own: it is the same resource, the same grant, the same
+    // backfill and the same `rows_indexed`/`already_existed`/`duplicate_values`
+    // vocabulary, and GET has to report both halves anyway. A second route would
+    // duplicate all of that and leave a caller two places to look for "what
+    // does this collection enforce". The two spellings are mutually exclusive -
+    // see parseIndexRequest().
     svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes)",
              [d](const httplib::Request& req, httplib::Response& res) {
         ApiKey k = requireKey(*d, req);
         std::string project = req.matches[1], coll = req.matches[2];
         requireProjectManage(k, project);
-        auto body = bodyJson(req);
-        // A request body of literal `null` (or any non-object JSON) parses fine but
-        // is not an object; guard before .value() so it 422s as "missing field"
-        // rather than 500ing on a type_error.
-        std::string field = body.is_object() ? body.value("field", "") : std::string();
-        if (field.empty()) throw ApiError(ErrCode::Unprocessable, "validation", "field is required");
+        const IndexRequest want = parseIndexRequest(bodyJson(req));
 
         const std::string qc = qualify(project, coll);
         if (!d->db.client().getCollectionInfo(qc))
             throw ApiError(ErrCode::NotFound, "not_found", "collection not found");
 
-        const bool unique = body.value("unique", false);
-        if (unique) {
+        if (want.composite()) {
+            auto r = d->db.client().createCompositeUniqueIndex(qc, want.fields);
+            if (!r.success)
+                throw indexDeclineError(r, "the combination of fields");
+            nlohmann::json out = compositeJson(want.fields);
+            out["rows_indexed"] = r.rowsIndexed;
+            out["already_existed"] = r.alreadyExisted;
+            sendJson(res, 201, out);
+            return;
+        }
+
+        const std::string& field = want.field;
+        if (want.unique) {
             auto r = d->db.client().createUniqueIndex(qc, field);
-            if (!r.success) {
-                if (!r.duplicateExamples.empty()) {
-                    nlohmann::json ex = nlohmann::json::array();
-                    for (const auto& id : r.duplicateExamples) ex.push_back(id);
-                    throw ApiError(ErrCode::Conflict, "duplicate_values",
-                                   "field '" + field + "' already holds duplicate values",
-                                   {{"duplicate_examples", ex}});
-                }
-                throw ApiError(ErrCode::Unavailable, "db_error",
-                               r.error.empty() ? "failed to create unique index" : r.error);
-            }
+            if (!r.success)
+                throw indexDeclineError(r, "field '" + field + "'");
             sendJson(res, 201, {{"field", field}, {"unique", true},
                                 {"rows_indexed", r.rowsIndexed},
                                 {"already_existed", r.alreadyExisted}});
@@ -83,7 +120,63 @@ void registerIndexRoutes(ApiServer& s) {
                            {"entries", def.entries},
                            {"unique", uniq}});
         }
-        sendJson(res, 200, {{"indexes", out}});
+
+        // A separate key, not extra entries in `indexes`: a composite backs no
+        // query, so it has no `distinct_values` and no `entries`, and it is
+        // named by a list rather than by a field. Mixing the two would mean
+        // rows in one array whose keys differ, which every existing reader of
+        // this response would have to be taught about. Additive instead.
+        nlohmann::json composites = nlohmann::json::array();
+        try {
+            for (const auto& fields : d->db.client().listCompositeUniqueIndexes(qc))
+                composites.push_back(compositeJson(fields));
+        } catch (const smartbotic::database::Client::Error& e) {
+            // Classified rather than swallowed: an empty list here would read
+            // as "this collection enforces nothing", which is the one wrong
+            // answer to give about a constraint.
+            throw apiErrorFor(e);
+        }
+        sendJson(res, 200, {{"indexes", out}, {"composite_unique", composites}});
+    });
+
+    // Drop a composite constraint, named by its exact field list.
+    //
+    // The field list lives in a repeatable query parameter because it cannot
+    // live in the path: joining it would need a separator no field name may
+    // contain, and a reserved segment (".../indexes/composite") would shadow a
+    // real field of that name. On the collection-level path rather than under
+    // `/indexes/{field}`, so it cannot be confused with the single-field drop.
+    // An empty `fields` is a 422, never "drop everything".
+    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes)",
+               [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        std::string project = req.matches[1], coll = req.matches[2];
+        requireProjectManage(k, project);
+
+        std::vector<std::string> raw;
+        auto range = req.params.equal_range("fields");
+        for (auto it = range.first; it != range.second; ++it) raw.push_back(it->second);
+        const std::vector<std::string> fields = parseCompositeFieldsParam(std::move(raw));
+
+        bool dropped = false;
+        try {
+            dropped = d->db.client().dropCompositeUniqueIndex(qualify(project, coll), fields);
+        } catch (const smartbotic::database::Client::Error& e) {
+            throw apiErrorFor(e);
+        }
+        // NOT 404 on false. A drop is idempotent at the database - dropping a
+        // constraint that is not there reaches the requested end state and
+        // succeeds - so `false` never means "no such constraint". It means the
+        // call itself failed: a read-only database, a config write that did not
+        // land, or a dead connection. Answering 404 to those would tell the
+        // caller their constraint is gone when it is still being enforced.
+        if (!dropped)
+            throw ApiError(ErrCode::Unavailable, "unavailable",
+                           "the database did not apply the drop");
+        // `dropped_fields`, not `dropped`: the single-field drop answers with a
+        // string under that name, and one key whose type depends on the route
+        // is how a client ends up with a crash instead of a branch.
+        sendJson(res, 200, {{"dropped_fields", fields}});
     });
 
     // Distinct values of an indexed field, with counts. Index-dependent by
@@ -115,8 +208,11 @@ void registerIndexRoutes(ApiServer& s) {
         ApiKey k = requireKey(*d, req);
         std::string project = req.matches[1], coll = req.matches[2], field = req.matches[3];
         requireProjectManage(k, project);
+        // Idempotent, and `false` is a failed call rather than a missing index -
+        // see the composite drop above for why that is not a 404.
         if (!d->db.client().dropIndex(qualify(project, coll), field))
-            throw ApiError(ErrCode::NotFound, "not_found", "index not found");
+            throw ApiError(ErrCode::Unavailable, "unavailable",
+                           "the database did not apply the drop");
         sendJson(res, 200, {{"dropped", field}});
     });
 }

+ 143 - 0
src/index_request.hpp

@@ -0,0 +1,143 @@
+#pragma once
+#include "errors.hpp"
+#include <nlohmann/json.hpp>
+#include <algorithm>
+#include <string>
+#include <vector>
+
+/// The pure half of the index routes: what a caller asked POST /indexes to
+/// declare, and which composite constraint a DELETE named.
+///
+/// Header-only and dependent on nothing but nlohmann/json and `errors.hpp`, so
+/// the request grammar can be exercised without a database client - the
+/// handlers in `handlers/indexes.cpp` link the world and cannot be instantiated
+/// in a unit test. Same split, and same reason, as `documents_util.hpp`.
+namespace svapi {
+
+/// What POST /indexes was asked for: a single-field index, or a composite
+/// unique constraint over two or more fields. Never both - see
+/// parseIndexRequest().
+struct IndexRequest {
+    std::string              field;    ///< empty for a composite request
+    std::vector<std::string> fields;   ///< empty for a single-field request
+    bool                     unique = false;
+
+    bool composite() const { return !fields.empty(); }
+};
+
+/// A field name a composite constraint may name.
+///
+/// A dotted path addresses a nested field, so an empty segment ("a..b", ".a",
+/// "a.") addresses nothing: the database would store a constraint that can
+/// never match the document the caller had in mind. Refused here rather than
+/// declared and left to behave oddly forever.
+inline void validateIndexFieldPath(const std::string& f, const char* what) {
+    if (f.empty())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(what) + " must not contain an empty field name");
+    if (f.front() == '.' || f.back() == '.' || f.find("..") != std::string::npos)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(what) + " contains an empty path segment: '" + f + "'");
+}
+
+/// The field list identifying a composite unique constraint.
+///
+/// Two or more fields, each named once. One field is not a composite - the
+/// caller means the single-field form, and silently accepting a one-element
+/// list would create a constraint that `DELETE /indexes/{field}` cannot drop
+/// and `GET` reports in the other half of the response. A repeated field is
+/// refused because the database identifies a composite by its EXACT list, so
+/// ("a","a") and ("a") would be two constraints enforcing one rule.
+inline std::vector<std::string> validateCompositeFields(std::vector<std::string> fields,
+                                                        const char* what) {
+    if (fields.size() < 2)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(what) + " must name at least two fields; "
+                       "use the single-field form for one");
+    for (const std::string& f : fields) validateIndexFieldPath(f, what);
+    std::vector<std::string> sorted = fields;
+    std::sort(sorted.begin(), sorted.end());
+    if (std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       std::string(what) + " must not repeat a field");
+    return fields;
+}
+
+/// Read a POST /indexes body.
+///
+/// `field` and `fields` are two spellings of one request and are mutually
+/// exclusive: a body carrying both is refused rather than resolved by
+/// precedence. Picking one would make the caller's second intent vanish with
+/// nothing in the response to say so, and the two are not interchangeable - a
+/// constraint over (a, b) is not the constraint over (a) a reader of the code
+/// would guess. Both KEYS are the ambiguity, whatever their values, so this
+/// tests presence and not emptiness: `{"field": null, "fields": [...]}` is a
+/// caller that does not know which form it is sending.
+inline IndexRequest parseIndexRequest(const nlohmann::json& body) {
+    // A body of literal `null` (or any non-object JSON) parses fine but has no
+    // keys; it must reach the "nothing was named" refusal rather than throw a
+    // type_error out of .at() and become a 500.
+    const bool obj = body.is_object();
+    const bool hasField  = obj && body.contains("field");
+    const bool hasFields = obj && body.contains("fields");
+
+    if (hasField && hasFields)
+        throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
+                       "'field' and 'fields' are two spellings of one request and cannot be "
+                       "combined: send 'field' for a single-field index, or 'fields' for a "
+                       "composite unique constraint");
+
+    IndexRequest out;
+
+    if (hasFields) {
+        const nlohmann::json& f = body.at("fields");
+        if (!f.is_array())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "fields must be an array of field names");
+        std::vector<std::string> names;
+        for (const auto& entry : f) {
+            if (!entry.is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "fields must be an array of field names");
+            names.push_back(entry.get<std::string>());
+        }
+        out.fields = validateCompositeFields(std::move(names), "fields");
+        // A composite exists only as a unique constraint: the database offers
+        // no composite secondary index, and it backs no query. `unique` may be
+        // omitted (it is implied) or stated as true, but an explicit `false` is
+        // a caller asking for something that does not exist, and answering 201
+        // would hand it a uniqueness guarantee it believes it declined.
+        if (body.contains("unique") && !body.at("unique").is_null()) {
+            if (!body.at("unique").is_boolean() || !body.at("unique").get<bool>())
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "a composite 'fields' declaration is always a unique constraint; "
+                               "omit 'unique' or send unique:true");
+        }
+        out.unique = true;
+        return out;
+    }
+
+    out.field = (hasField && body.at("field").is_string())
+                    ? body.at("field").get<std::string>() : std::string();
+    if (out.field.empty())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "field is required (or 'fields' for a composite unique constraint)");
+    out.unique = body.value("unique", false);
+    return out;
+}
+
+/// The composite constraint a `DELETE /indexes?fields=a&fields=b` named.
+///
+/// A repeatable query parameter rather than a path segment because a composite
+/// is identified by its exact field LIST: a joined path segment would need a
+/// separator that no field name may contain, and a reserved segment under
+/// `/indexes/{field}` would collide with a real field of that name.
+inline std::vector<std::string> parseCompositeFieldsParam(std::vector<std::string> values) {
+    if (values.empty())
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "fields is required: name every field of the composite constraint, "
+                       "e.g. ?fields=chat_id&fields=file_unique_id");
+    return validateCompositeFields(std::move(values), "fields");
+}
+
+} // namespace svapi

+ 12 - 0
tests/CMakeLists.txt

@@ -205,3 +205,15 @@ target_include_directories(test_project_secret_store PRIVATE
 target_link_libraries(test_project_secret_store PRIVATE
     nlohmann_json::nlohmann_json GTest::gtest_main)
 gtest_discover_tests(test_project_secret_store)
+
+# The index request grammar: pure, so it builds where the database client cannot.
+add_executable(test_index_request test_index_request.cpp)
+target_include_directories(test_index_request PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_index_request PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_index_request)
+
+# Document body shaping and the increment deltas: header-only and pure.
+add_executable(test_documents_util test_documents_util.cpp)
+target_include_directories(test_documents_util PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_documents_util PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_documents_util)

+ 24 - 2
tests/api_fixture.hpp

@@ -44,9 +44,31 @@ protected:
         project_ = tmpName("apiproj");
         db_->client().dropCollection(settingsColl_);
         db_->client().dropCollection(keysColl_);
+        // Purge the previous run before dropping the project. Two database
+        // caveats make this necessary, and both are invisible against a
+        // throw-away database, which is why this only ever mattered once the
+        // suite could run against a persistent one:
+        //   - dropProject does not delete collection data, so the collections
+        //     a previous run created still hold their documents; and
+        //   - dropCollection does not clear the collection's INDEX
+        //     declarations, so a unique index declared last run survives into
+        //     this one. A test that declares it again then gets
+        //     already_existed (success) where it expects a refusal.
+        // Dropping each index before its collection is therefore the only way
+        // to reach a clean slate. The project name is fixed, so without this
+        // the suite is not idempotent.
+        {
+            CollectionRegistry stale(*db_);
+            for (const auto& m : stale.list(project_)) {
+                const std::string qc = qualify(project_, m.name);
+                for (const auto& idx : db_->client().listIndexes(qc))
+                    db_->client().dropIndex(qc, idx.field);
+                for (const auto& fields : db_->client().listCompositeUniqueIndexes(qc))
+                    db_->client().dropCompositeUniqueIndex(qc, fields);
+                db_->client().dropCollection(qc);
+            }
+        }
         db_->dropProject(project_);
-        // DB v2.3.1 Stage-F caveat: dropProject does not delete collection data.
-        // Drop the project's registry collection explicitly so ensure() starts fresh.
         db_->client().dropCollection(qualify(project_, "vectorapi_collections"));
         db_->ensureProject(project_);
 

+ 361 - 10
tests/test_api_integration.cpp

@@ -249,7 +249,7 @@ TEST_F(ApiFixture, ProjectRecycleAfterDelete) {
     ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","users"},{"kind","json"}}.dump(), "application/json")->status, 201);
     // Delete the project (should purge collections + registry)
     ASSERT_EQ(c.Delete(("/api/v1/projects/" + p2).c_str())->status, 200);
-    // Re-create project and collection — must succeed (201, not 422)
+    // Re-create project and collection - must succeed (201, not 422)
     ASSERT_EQ(c.Post("/api/v1/projects", nlohmann::json{{"name", p2}}.dump(), "application/json")->status, 201);
     auto r = c.Post(base.c_str(), nlohmann::json{{"name","users"},{"kind","json"}}.dump(), "application/json");
     ASSERT_TRUE(r);
@@ -532,7 +532,7 @@ TEST_F(ApiFixture, EmbeddingCacheBypassedByNoCacheControlHeader) {
 // in a key scope; a leaked publishable key must not be able to wipe the catalog.
 TEST_F(ApiFixture, ScopedKeyCannotManageCollections) {
     // Build a capability-scoped key directly in the DB (key create API does not yet
-    // expose scope on POST — that is task U4). The key is granted project_ with a
+    // expose scope on POST - that is task U4). The key is granted project_ with a
     // single data-level rule so it is a real scoped key (k.scope is populated).
     svapi::ApiKey scopedKey;
     scopedKey.id        = svapi::generateApiKey();
@@ -551,18 +551,18 @@ TEST_F(ApiFixture, ScopedKeyCannotManageCollections) {
     }
     // Insert directly into the key collection so the server's KeyStore picks it up.
     db_->client().upsert(keysColl_, scopedKey.toJson(), scopedKey.id);
-    keys_->bootstrap("");   // triggers reload() — bootstrap is idempotent if keys exist
+    keys_->bootstrap("");   // triggers reload() - bootstrap is idempotent if keys exist
 
     const std::string base = "/api/v1/projects/" + project_ + "/collections";
     auto scoped = http(scopedKey.key);
 
-    // POST /collections — scoped key must be denied (403)
+    // POST /collections - scoped key must be denied (403)
     auto createRes = scoped.Post(base.c_str(),
         nlohmann::json{{"name", "scopedtest"}, {"kind", "json"}}.dump(), "application/json");
     ASSERT_TRUE(createRes);
     EXPECT_EQ(createRes->status, 403) << "scoped key must not create collections; body: " << createRes->body;
 
-    // DELETE /collections/<name> — scoped key must be denied (403)
+    // DELETE /collections/<name> - scoped key must be denied (403)
     auto delRes = scoped.Delete((base + "/any_collection").c_str());
     ASSERT_TRUE(delRes);
     EXPECT_EQ(delRes->status, 403) << "scoped key must not delete collections; body: " << delRes->body;
@@ -578,7 +578,7 @@ TEST_F(ApiFixture, ScopedKeyCannotManageCollections) {
     db_->client().remove(keysColl_, scopedKey.id);
 }
 
-// U5a: scoped key op+collection matrix — only explicitly granted (collection, op) pairs succeed.
+// U5a: scoped key op+collection matrix - only explicitly granted (collection, op) pairs succeed.
 TEST_F(ApiFixture, ScopedKeyOpAndCollectionMatrix) {
     // Create collections: designs (json), quotes (json), other (json).
     const std::string base = "/api/v1/projects/" + project_ + "/collections";
@@ -664,7 +664,7 @@ TEST_F(ApiFixture, ScopedKeyOpAndCollectionMatrix) {
     db_->client().remove(keysColl_, sk.id);
 }
 
-// U5b: scoped key with an origins list enforces the Origin header — fails closed (no header → 403).
+// U5b: scoped key with an origins list enforces the Origin header - fails closed (no header → 403).
 TEST_F(ApiFixture, ScopedKeyOriginEnforced) {
     const std::string base = "/api/v1/projects/" + project_ + "/collections";
     ASSERT_EQ(admin().Post(base.c_str(),
@@ -1001,16 +1001,21 @@ TEST_F(ApiFixture, IndexValuesRejectsOutOfRangeLimit) {
     ASSERT_TRUE(absent); EXPECT_EQ(absent->status, 200);
 }
 
+// Named "uqdup" rather than "uq": a database run before the index-undeclare
+// fixes left a unique sku index declared on the dead collection
+// svapitest_apiproj:uq, and that declaration cannot be removed through any
+// client call, so the old name reports already_existed forever on a persistent
+// database. See the dropCollection caveat in CLAUDE.md.
 TEST_F(ApiFixture, UniqueIndexRejectsExistingDuplicates) {
     auto c = admin();
     std::string base = "/api/v1/projects/" + project_ + "/collections";
-    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","uq"},{"kind","json"}}.dump(),
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","uqdup"},{"kind","json"}}.dump(),
                      "application/json")->status, 201);
-    std::string docs = base + "/uq/documents";
+    std::string docs = base + "/uqdup/documents";
     ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"sku","A1"}}.dump(), "application/json")->status, 201);
     ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"sku","A1"}}.dump(), "application/json")->status, 201);
 
-    auto conflict = c.Post((base + "/uq/indexes").c_str(),
+    auto conflict = c.Post((base + "/uqdup/indexes").c_str(),
                            nlohmann::json{{"field","sku"},{"unique",true}}.dump(), "application/json");
     ASSERT_TRUE(conflict); EXPECT_EQ(conflict->status, 409);
     auto body = nlohmann::json::parse(conflict->body);
@@ -2105,3 +2110,349 @@ TEST_F(ApiFixture, ScopedUpdateOnlyKeyCannotCreateViaPut) {
 
     db_->client().remove(keysColl_, sk.id);
 }
+
+// --- Composite unique constraints (database 2.12.0) -------------------------
+//
+// A composite is declared on the SAME route as a single-field index, with
+// `fields` instead of `field`: same grant, same backfill, same
+// rows_indexed/already_existed/duplicate_values vocabulary. These tests pin the
+// three things a caller can get wrong (both spellings at once, one field, an
+// explicit unique:false) and the one thing the feature is for - that the
+// COMBINATION is enforced while a single column stays free to repeat.
+
+TEST_F(ApiFixture, CompositeUniqueIndexDeclareEnforceListDrop) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cuq"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string idx  = base + "/cuq/indexes";
+    const std::string docs = base + "/cuq/documents";
+
+    auto made = c.Post(idx.c_str(),
+                       nlohmann::json{{"fields",{"chat_id","file_unique_id"}}}.dump(),
+                       "application/json");
+    ASSERT_TRUE(made); ASSERT_EQ(made->status, 201) << made->body;
+    auto madeJson = nlohmann::json::parse(made->body);
+    ASSERT_TRUE(madeJson.contains("fields"));
+    EXPECT_EQ(madeJson["fields"], nlohmann::json({"chat_id","file_unique_id"}));
+    EXPECT_TRUE(madeJson["unique"].get<bool>());
+    EXPECT_TRUE(madeJson.contains("already_existed"));
+
+    // Re-declaring is idempotent, exactly as it is for a single field.
+    auto again = c.Post(idx.c_str(),
+                        nlohmann::json{{"fields",{"chat_id","file_unique_id"}}}.dump(),
+                        "application/json");
+    ASSERT_TRUE(again); EXPECT_EQ(again->status, 201) << again->body;
+    EXPECT_TRUE(nlohmann::json::parse(again->body)["already_existed"].get<bool>());
+
+    // GET keeps its existing shape for single-field indexes and reports the
+    // composite under its own key - a new key, so an existing reader of
+    // `indexes` is untouched.
+    auto list = c.Get(idx.c_str());
+    ASSERT_TRUE(list); ASSERT_EQ(list->status, 200) << list->body;
+    auto listJson = nlohmann::json::parse(list->body);
+    ASSERT_TRUE(listJson.contains("indexes"));
+    ASSERT_TRUE(listJson.contains("composite_unique"));
+    bool found = false;
+    for (auto& e : listJson["composite_unique"]) {
+        if (e["fields"] == nlohmann::json({"chat_id","file_unique_id"})) {
+            found = true;
+            EXPECT_TRUE(e["unique"].get<bool>());
+        }
+    }
+    EXPECT_TRUE(found) << list->body;
+
+    // The COMBINATION is what is constrained: either column alone may repeat.
+    ASSERT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"chat_id",1},{"file_unique_id","f1"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"chat_id",1},{"file_unique_id","f2"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"chat_id",2},{"file_unique_id","f1"}}.dump(),
+                     "application/json")->status, 201);
+
+    auto dup = c.Post(docs.c_str(),
+                      nlohmann::json{{"chat_id",1},{"file_unique_id","f1"}}.dump(),
+                      "application/json");
+    ASSERT_TRUE(dup); EXPECT_EQ(dup->status, 409) << dup->body;
+    EXPECT_EQ(nlohmann::json::parse(dup->body)["error"]["code"], "duplicate_values");
+
+    // Dropped by its exact field list, in a repeatable query parameter.
+    auto dropped = c.Delete((idx + "?fields=chat_id&fields=file_unique_id").c_str());
+    ASSERT_TRUE(dropped); EXPECT_EQ(dropped->status, 200) << dropped->body;
+    EXPECT_EQ(nlohmann::json::parse(dropped->body)["dropped_fields"],
+              nlohmann::json({"chat_id","file_unique_id"}));
+
+    // Gone from the listing, and the write it refused now succeeds.
+    auto after = nlohmann::json::parse(c.Get(idx.c_str())->body);
+    for (auto& e : after["composite_unique"])
+        EXPECT_NE(e["fields"], nlohmann::json({"chat_id","file_unique_id"}));
+    EXPECT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"chat_id",1},{"file_unique_id","f1"}}.dump(),
+                     "application/json")->status, 201);
+}
+
+// A document missing any of the fields does not participate, which is the SQL
+// rule for a NULL in a unique key. Worth an integration test because it is the
+// one part of the semantics the API cannot see: it is enforced in the database.
+TEST_F(ApiFixture, CompositeUniqueIgnoresAbsentAndNullFields) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cuqnull"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post((base + "/cuqnull/indexes").c_str(),
+                     nlohmann::json{{"fields",{"chat_id","file_unique_id"}}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/cuqnull/documents";
+
+    // Same chat_id, file_unique_id absent in both: not constrained.
+    EXPECT_EQ(c.Post(docs.c_str(), nlohmann::json{{"chat_id",9}}.dump(),
+                     "application/json")->status, 201);
+    EXPECT_EQ(c.Post(docs.c_str(), nlohmann::json{{"chat_id",9}}.dump(),
+                     "application/json")->status, 201);
+
+    // Same again with an explicit null.
+    EXPECT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"chat_id",10},{"file_unique_id",nullptr}}.dump(),
+                     "application/json")->status, 201);
+    EXPECT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"chat_id",10},{"file_unique_id",nullptr}}.dump(),
+                     "application/json")->status, 201);
+}
+
+// Declaring a composite over rows that ALREADY collide is refused, with the
+// colliding ids - the same answer, and the same slug, as the single-field case.
+TEST_F(ApiFixture, CompositeUniqueIndexRejectsExistingDuplicates) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cuqdup"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/cuqdup/documents";
+    for (int i = 0; i < 2; ++i)
+        ASSERT_EQ(c.Post(docs.c_str(),
+                         nlohmann::json{{"chat_id",5},{"file_unique_id","same"}}.dump(),
+                         "application/json")->status, 201);
+
+    auto conflict = c.Post((base + "/cuqdup/indexes").c_str(),
+                           nlohmann::json{{"fields",{"chat_id","file_unique_id"}}}.dump(),
+                           "application/json");
+    ASSERT_TRUE(conflict); ASSERT_EQ(conflict->status, 409) << conflict->body;
+    auto body = nlohmann::json::parse(conflict->body);
+    EXPECT_EQ(body["error"]["code"], "duplicate_values");
+    ASSERT_TRUE(body["error"]["details"].contains("duplicate_examples"));
+    EXPECT_GE(body["error"]["details"]["duplicate_examples"].size(), 1u);
+}
+
+// `field` and `fields` are two spellings of one request. Sending both is
+// refused rather than resolved by precedence, which would silently discard one
+// of the caller's two intents.
+TEST_F(ApiFixture, IndexCreateRefusesFieldAndFieldsTogether) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cuqamb"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+
+    auto both = c.Post((base + "/cuqamb/indexes").c_str(),
+                       nlohmann::json{{"field","chat_id"},{"fields",{"chat_id","file_unique_id"}}}.dump(),
+                       "application/json");
+    ASSERT_TRUE(both); EXPECT_EQ(both->status, 422) << both->body;
+    EXPECT_EQ(nlohmann::json::parse(both->body)["error"]["code"], "ambiguous_body");
+
+    // Nothing was declared by the refused request.
+    auto list = nlohmann::json::parse(c.Get((base + "/cuqamb/indexes").c_str())->body);
+    EXPECT_TRUE(list["composite_unique"].empty()) << list.dump();
+}
+
+TEST_F(ApiFixture, CompositeIndexRequestValidation) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cuqval"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string idx = base + "/cuqval/indexes";
+    const std::string ct = "application/json";
+
+    // One field is not a composite; the caller means the single-field form.
+    EXPECT_EQ(c.Post(idx.c_str(), nlohmann::json{{"fields",{"chat_id"}}}.dump(), ct)->status, 422);
+    // A composite exists only as a unique constraint.
+    EXPECT_EQ(c.Post(idx.c_str(),
+                     nlohmann::json{{"fields",{"a","b"}},{"unique",false}}.dump(), ct)->status, 422);
+    // Identified by its exact list, so a repeated field is two constraints for one rule.
+    EXPECT_EQ(c.Post(idx.c_str(), nlohmann::json{{"fields",{"a","a"}}}.dump(), ct)->status, 422);
+    EXPECT_EQ(c.Post(idx.c_str(), nlohmann::json{{"fields",{"a",7}}}.dump(), ct)->status, 422);
+    EXPECT_EQ(c.Post(idx.c_str(), nlohmann::json{{"fields","a,b"}}.dump(), ct)->status, 422);
+    EXPECT_EQ(c.Post(idx.c_str(), nlohmann::json{{"fields",{"a",""}}}.dump(), ct)->status, 422);
+}
+
+// The drop never means "drop everything": an unnamed or single-field list is a
+// client whose query-string building went wrong, and gets 422. A list naming no
+// existing constraint is NOT an error - the database's drop is idempotent, so
+// the requested end state is already reached and the answer is 200. That is
+// also why a falsey drop must not be reported as 404: it means the call failed.
+TEST_F(ApiFixture, CompositeIndexDropValidation) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cuqdrop"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string idx = base + "/cuqdrop/indexes";
+
+    EXPECT_EQ(c.Delete(idx.c_str())->status, 422);
+    EXPECT_EQ(c.Delete((idx + "?fields=chat_id").c_str())->status, 422);
+    EXPECT_EQ(c.Delete((idx + "?fields=a&fields=a").c_str())->status, 422);
+    // Idempotent, and it echoes back exactly what the caller named.
+    auto gone = c.Delete((idx + "?fields=nope_a&fields=nope_b").c_str());
+    ASSERT_EQ(gone->status, 200);
+    EXPECT_EQ(nlohmann::json::parse(gone->body)["dropped_fields"],
+              nlohmann::json({"nope_a", "nope_b"}));
+    // Dropping twice is the same answer, which is what idempotent has to mean.
+    EXPECT_EQ(c.Delete((idx + "?fields=nope_a&fields=nope_b").c_str())->status, 200);
+}
+
+// --- Atomic increment (database 2.12.0) ------------------------------------
+
+TEST_F(ApiFixture, IncrementAddsAndReturnsNewValues) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","counters"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/counters/documents";
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"id","day-1"},{"calls",17}}.dump(),
+                     "application/json")->status, 201);
+
+    // `minutes` is absent and counts as 0, so it comes back as the delta itself.
+    auto bumped = c.Post((docs + "/day-1/increment").c_str(),
+                         nlohmann::json{{"calls",1},{"minutes",3.5}}.dump(), "application/json");
+    ASSERT_TRUE(bumped); ASSERT_EQ(bumped->status, 200) << bumped->body;
+    auto body = nlohmann::json::parse(bumped->body);
+    EXPECT_EQ(body["id"], "day-1");
+    ASSERT_TRUE(body.contains("values"));
+    EXPECT_EQ(body["values"]["calls"], 18);
+    EXPECT_DOUBLE_EQ(body["values"]["minutes"].get<double>(), 3.5);
+
+    // A negative delta decrements; the stored document agrees with the answer.
+    auto down = c.Post((docs + "/day-1/increment").c_str(),
+                       nlohmann::json{{"calls",-8}}.dump(), "application/json");
+    ASSERT_TRUE(down); ASSERT_EQ(down->status, 200) << down->body;
+    EXPECT_EQ(nlohmann::json::parse(down->body)["values"]["calls"], 10);
+    auto stored = nlohmann::json::parse(c.Get((docs + "/day-1").c_str())->body);
+    EXPECT_EQ(stored["calls"], 10);
+
+    // A dotted key addresses a nested field.
+    auto nested = c.Post((docs + "/day-1/increment").c_str(),
+                         nlohmann::json{{"counts.sent",2}}.dump(), "application/json");
+    ASSERT_TRUE(nested); ASSERT_EQ(nested->status, 200) << nested->body;
+    auto deep = nlohmann::json::parse(c.Get((docs + "/day-1").c_str())->body);
+    EXPECT_EQ(deep["counts"]["sent"], 2) << deep.dump();
+
+    // The `{"data":...}` wrapper works here too, so a client that wraps every
+    // body does not have to stop wrapping for this one route.
+    auto wrapped = c.Post((docs + "/day-1/increment").c_str(),
+                          nlohmann::json{{"data",{{"calls",1}}}}.dump(), "application/json");
+    ASSERT_TRUE(wrapped); ASSERT_EQ(wrapped->status, 200) << wrapped->body;
+    EXPECT_EQ(nlohmann::json::parse(wrapped->body)["values"]["calls"], 11);
+}
+
+// It never creates: the starting document is the caller's to describe, and the
+// documented idiom is increment -> 404 -> POST at a fixed id -> increment again.
+TEST_F(ApiFixture, IncrementRequiresTheDocumentToExist) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","counters404"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/counters404/documents";
+
+    auto missing = c.Post((docs + "/never-made/increment").c_str(),
+                          nlohmann::json{{"calls",1}}.dump(), "application/json");
+    ASSERT_TRUE(missing); EXPECT_EQ(missing->status, 404) << missing->body;
+    EXPECT_EQ(c.Get((docs + "/never-made").c_str())->status, 404);
+
+    // The idiom, end to end.
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"id","never-made"},{"calls",1}}.dump(),
+                     "application/json")->status, 201);
+    auto now = c.Post((docs + "/never-made/increment").c_str(),
+                      nlohmann::json{{"calls",1}}.dump(), "application/json");
+    ASSERT_TRUE(now); ASSERT_EQ(now->status, 200) << now->body;
+    EXPECT_EQ(nlohmann::json::parse(now->body)["values"]["calls"], 2);
+}
+
+// The whole set applies or none of it does, so a non-number anywhere must leave
+// every other counter in the request untouched.
+TEST_F(ApiFixture, IncrementRejectsNonNumbersAndAppliesNothing) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","counters422"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/counters422/documents";
+    ASSERT_EQ(c.Post(docs.c_str(),
+                     nlohmann::json{{"id","d"},{"calls",4},{"label","hello"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string inc = docs + "/d/increment";
+    const std::string ct = "application/json";
+
+    // Our own refusals: a non-numeric delta, an empty body, an empty path
+    // segment, and `data` beside siblings.
+    EXPECT_EQ(c.Post(inc.c_str(), nlohmann::json{{"calls","1"}}.dump(), ct)->status, 422);
+    EXPECT_EQ(c.Post(inc.c_str(), nlohmann::json{{"calls",true}}.dump(), ct)->status, 422);
+    EXPECT_EQ(c.Post(inc.c_str(), nlohmann::json::object().dump(), ct)->status, 422);
+    EXPECT_EQ(c.Post(inc.c_str(), nlohmann::json{{"counts..sent",1}}.dump(), ct)->status, 422);
+    auto ambiguous = c.Post(inc.c_str(),
+                            nlohmann::json{{"data",{{"calls",1}}},{"minutes",1}}.dump(), ct);
+    ASSERT_TRUE(ambiguous); ASSERT_EQ(ambiguous->status, 422) << ambiguous->body;
+    EXPECT_EQ(nlohmann::json::parse(ambiguous->body)["error"]["code"], "ambiguous_body");
+
+    // The database's own refusal: `label` holds a string. 422, and NOTHING is
+    // applied - `calls` must still be 4.
+    auto dbRefusal = c.Post(inc.c_str(), nlohmann::json{{"calls",1},{"label",1}}.dump(), ct);
+    ASSERT_TRUE(dbRefusal); EXPECT_EQ(dbRefusal->status, 422) << dbRefusal->body;
+    auto stored = nlohmann::json::parse(c.Get((docs + "/d").c_str())->body);
+    EXPECT_EQ(stored["calls"], 4) << stored.dump();
+    EXPECT_EQ(stored["label"], "hello");
+}
+
+// It is a WRITE: a scope granting only `read` must not reach it, and `update`
+// is what authorizes it - the same grant that could already set the number
+// directly.
+TEST_F(ApiFixture, IncrementNeedsTheUpdateGrant) {
+    auto c = admin();
+    std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","counters403"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/counters403/documents";
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"id","d"},{"calls",1}}.dump(),
+                     "application/json")->status, 201);
+    const std::string inc = docs + "/d/increment";
+
+    auto makeKey = [&](std::set<svapi::KeyOp> ops) {
+        svapi::ApiKey sk;
+        sk.id        = svapi::generateApiKey();
+        sk.key       = svapi::generateApiKey();
+        sk.label     = "increment-grant";
+        sk.projects  = {project_};
+        sk.admin     = false;
+        sk.createdAt = 0;
+        svapi::KeyScope sc;
+        svapi::KeyScopeRule r;
+        r.collection = "counters403";
+        r.ops        = std::move(ops);
+        sc.rules.push_back(std::move(r));
+        sk.scope = sc;
+        db_->client().upsert(keysColl_, sk.toJson(), sk.id);
+        keys_->bootstrap("");
+        return sk;
+    };
+
+    svapi::ApiKey readOnly = makeKey({svapi::KeyOp::Read});
+    auto denied = http(readOnly.key).Post(inc.c_str(), nlohmann::json{{"calls",1}}.dump(),
+                                          "application/json");
+    ASSERT_TRUE(denied); EXPECT_EQ(denied->status, 403) << denied->body;
+    EXPECT_EQ(nlohmann::json::parse(admin().Get((docs + "/d").c_str())->body)["calls"], 1);
+    db_->client().remove(keysColl_, readOnly.id);
+
+    svapi::ApiKey writer = makeKey({svapi::KeyOp::Update});
+    auto allowed = http(writer.key).Post(inc.c_str(), nlohmann::json{{"calls",1}}.dump(),
+                                         "application/json");
+    ASSERT_TRUE(allowed); EXPECT_EQ(allowed->status, 200) << allowed->body;
+    EXPECT_EQ(nlohmann::json::parse(allowed->body)["values"]["calls"], 2);
+    db_->client().remove(keysColl_, writer.id);
+}

+ 164 - 0
tests/test_documents_util.cpp

@@ -0,0 +1,164 @@
+// The pure half of the document handlers: body shaping and the increment
+// deltas. Header-only and database-free, which is the whole reason these rules
+// live in `documents_util.hpp` instead of inside the handlers.
+//
+// The increment deltas get the most attention here because the database applies
+// the whole set or nothing: one non-number anywhere refuses the entire call, so
+// a caller is better served by a refusal that names the field than by learning
+// afterwards that none of its five counters moved.
+#include <gtest/gtest.h>
+
+#include <cmath>
+#include <limits>
+
+#include "documents_util.hpp"
+
+using svapi::ApiError;
+using svapi::ErrCode;
+using svapi::documentBody;
+using svapi::incrementDeltas;
+using svapi::validateIncrementDeltas;
+using nlohmann::json;
+
+namespace {
+
+struct Refusal { ErrCode code; std::string slug; };
+
+template <typename F>
+Refusal refusalFrom(F&& f) {
+    try {
+        f();
+    } catch (const ApiError& e) {
+        return Refusal{e.code, e.slug};
+    }
+    return Refusal{ErrCode::Internal, "<no-throw>"};
+}
+
+}  // namespace
+
+TEST(IncrementDeltas, PlainBodyIsTheDeltaMap) {
+    json d = incrementDeltas(json{{"calls", 1}, {"minutes", 3.5}});
+    EXPECT_EQ(d["calls"], 1);
+    EXPECT_DOUBLE_EQ(d["minutes"].get<double>(), 3.5);
+}
+
+// The same two body shapes a document write accepts, for the same reason: a
+// client that wraps every body it sends should not have to stop wrapping here.
+TEST(IncrementDeltas, DataWrapperIsUnwrapped) {
+    json d = incrementDeltas(json{{"data", {{"calls", 2}}}});
+    ASSERT_TRUE(d.is_object());
+    EXPECT_EQ(d["calls"], 2);
+    EXPECT_FALSE(d.contains("data"));
+}
+
+TEST(IncrementDeltas, DataBesideSiblingsIsAmbiguous) {
+    Refusal r = refusalFrom([]{
+        incrementDeltas(json{{"data", {{"calls", 1}}}, {"minutes", 2}});
+    });
+    EXPECT_EQ(r.code, ErrCode::Unprocessable);
+    EXPECT_EQ(r.slug, "ambiguous_body");
+}
+
+TEST(IncrementDeltas, NegativeAndZeroDeltasAreLegal) {
+    json d = incrementDeltas(json{{"stock", -3}, {"touched", 0}});
+    EXPECT_EQ(d["stock"], -3);
+    EXPECT_EQ(d["touched"], 0);
+}
+
+TEST(IncrementDeltas, DottedPathsAreLegal) {
+    json d = incrementDeltas(json{{"counts.sent", 1}});
+    EXPECT_EQ(d["counts.sent"], 1);
+}
+
+// An empty map is a caller whose payload went wrong. Answering 200 with the
+// document's unchanged values would hide that completely.
+TEST(IncrementDeltas, EmptyBodyIsRejected) {
+    for (const json& body : {json::object(), json{{"data", json::object()}}}) {
+        Refusal r = refusalFrom([&]{ incrementDeltas(body); });
+        EXPECT_EQ(r.code, ErrCode::Unprocessable) << body.dump();
+        EXPECT_EQ(r.slug, "validation") << body.dump();
+    }
+}
+
+// `id` is the document's identity (it is in the URL for this route) and the
+// database's metadata is read-only, so documentBody() strips both - which
+// leaves nothing, and lands on the empty-body refusal rather than on a call
+// that tries to increment `_version`.
+TEST(IncrementDeltas, IdAndMetadataOnlyBodyIsRejected) {
+    for (const json& body : {json{{"id", "x"}}, json{{"_version", 2}}}) {
+        Refusal r = refusalFrom([&]{ incrementDeltas(body); });
+        EXPECT_EQ(r.slug, "validation") << body.dump();
+    }
+}
+
+TEST(IncrementDeltas, NonNumberValuesAreRejected) {
+    for (const json& body : {json{{"calls", "1"}},
+                             json{{"calls", true}},
+                             json{{"calls", nullptr}},
+                             json{{"calls", json::array({1})}},
+                             json{{"calls", json::object()}}}) {
+        Refusal r = refusalFrom([&]{ incrementDeltas(body); });
+        EXPECT_EQ(r.code, ErrCode::Unprocessable) << body.dump();
+        EXPECT_EQ(r.slug, "validation") << body.dump();
+    }
+}
+
+// One bad field refuses the whole call, matching what the database does: there
+// is no partial application to report, so there must be no partial acceptance.
+TEST(IncrementDeltas, OneBadFieldRefusesTheWholeSet) {
+    Refusal r = refusalFrom([]{
+        incrementDeltas(json{{"good", 1}, {"bad", "nope"}, {"alsoGood", 2}});
+    });
+    EXPECT_EQ(r.slug, "validation");
+}
+
+// A JSON document cannot carry NaN, but a delta map built in process can. A
+// counter that has become NaN cannot be compared, summed or recovered, and
+// nothing downstream would tell the caller when it happened.
+TEST(IncrementDeltas, NonFiniteDeltasAreRejected) {
+    for (double bad : {std::numeric_limits<double>::quiet_NaN(),
+                       std::numeric_limits<double>::infinity(),
+                       -std::numeric_limits<double>::infinity()}) {
+        Refusal r = refusalFrom([&]{ validateIncrementDeltas(json{{"calls", bad}}); });
+        EXPECT_EQ(r.slug, "validation");
+    }
+}
+
+TEST(IncrementDeltas, EmptyPathSegmentsAreRejected) {
+    for (const char* key : {".calls", "calls.", "counts..sent"}) {
+        Refusal r = refusalFrom([&]{ incrementDeltas(json{{key, 1}}); });
+        EXPECT_EQ(r.slug, "validation") << key;
+    }
+}
+
+TEST(IncrementDeltas, NonObjectBodyIsRejected) {
+    for (const json& body : {json(nullptr), json(7), json("calls"), json::array()}) {
+        Refusal r = refusalFrom([&]{ incrementDeltas(body); });
+        EXPECT_EQ(r.code, ErrCode::Unprocessable) << body.dump();
+    }
+}
+
+// A `{"data": 5}` wrapper unwraps to a non-object, which must refuse rather
+// than be handed to the database as a delta map.
+TEST(IncrementDeltas, DataWrapperAroundNonObjectIsRejected) {
+    Refusal r = refusalFrom([]{ incrementDeltas(json{{"data", 5}}); });
+    EXPECT_EQ(r.code, ErrCode::Unprocessable);
+    EXPECT_EQ(r.slug, "validation");
+}
+
+// documentBody() itself had no test before this file existed, and the increment
+// route is now a third caller of it, so its two shapes are pinned here too.
+TEST(DocumentBody, StripsIdAndMetadataFromBothShapes) {
+    json plain = documentBody(json{{"id", "x"}, {"_version", 3}, {"name", "a"}});
+    EXPECT_EQ(plain, (json{{"name", "a"}}));
+
+    json wrapped = documentBody(json{{"data", {{"id", "x"}, {"_updated_at", 1}, {"name", "a"}}}});
+    EXPECT_EQ(wrapped, (json{{"name", "a"}}));
+}
+
+// `id` beside `data` is NOT a sibling that makes the body ambiguous: POST reads
+// the document id from there.
+TEST(DocumentBody, IdBesideDataWrapperIsAllowed) {
+    json d = documentBody(json{{"id", "x"}, {"data", {{"name", "a"}}}});
+    EXPECT_EQ(d, (json{{"name", "a"}}));
+}

+ 193 - 0
tests/test_index_request.cpp

@@ -0,0 +1,193 @@
+// The POST /indexes request grammar and the composite drop's field list.
+//
+// Pure: `index_request.hpp` depends on nothing but nlohmann/json and
+// `errors.hpp`, which is why these rules are testable at all - the handler
+// links the database client and cannot be instantiated here.
+//
+// The rule worth pinning down is the REFUSAL: `field` and `fields` are two
+// spellings of one request, and a body carrying both must be rejected rather
+// than resolved by precedence. A precedence rule silently discards one of the
+// caller's two intents, and the two are not interchangeable - a constraint over
+// (a, b) is a different thing from the index on (a).
+#include <gtest/gtest.h>
+
+#include "index_request.hpp"
+
+using svapi::ApiError;
+using svapi::ErrCode;
+using svapi::IndexRequest;
+using svapi::parseCompositeFieldsParam;
+using svapi::parseIndexRequest;
+using nlohmann::json;
+
+namespace {
+
+// The slug and status a refusal carried, so a test asserts on the answer a
+// caller sees rather than on the message text.
+struct Refusal { ErrCode code; std::string slug; std::string message; };
+
+template <typename F>
+Refusal refusalFrom(F&& f) {
+    try {
+        f();
+    } catch (const ApiError& e) {
+        return Refusal{e.code, e.slug, e.what()};
+    }
+    return Refusal{ErrCode::Internal, "<no-throw>", ""};
+}
+
+}  // namespace
+
+TEST(IndexRequest, SingleFieldDefaultsToNonUnique) {
+    IndexRequest r = parseIndexRequest(json{{"field", "status"}});
+    EXPECT_FALSE(r.composite());
+    EXPECT_EQ(r.field, "status");
+    EXPECT_FALSE(r.unique);
+    EXPECT_TRUE(r.fields.empty());
+}
+
+TEST(IndexRequest, SingleFieldUniqueFlagIsCarried) {
+    IndexRequest r = parseIndexRequest(json{{"field", "sku"}, {"unique", true}});
+    EXPECT_EQ(r.field, "sku");
+    EXPECT_TRUE(r.unique);
+    EXPECT_FALSE(r.composite());
+}
+
+TEST(IndexRequest, MissingFieldIsRejected) {
+    Refusal r = refusalFrom([]{ parseIndexRequest(json::object()); });
+    EXPECT_EQ(r.code, ErrCode::Unprocessable);
+    EXPECT_EQ(r.slug, "validation");
+}
+
+// A body of literal `null` parses fine but is not an object. It must reach the
+// same "nothing was named" refusal rather than throw a type_error out of .at()
+// and surface as a 500.
+TEST(IndexRequest, NonObjectBodyIsRejectedAsValidation) {
+    for (const json& body : {json(nullptr), json(42), json("field"), json::array()}) {
+        Refusal r = refusalFrom([&]{ parseIndexRequest(body); });
+        EXPECT_EQ(r.code, ErrCode::Unprocessable) << body.dump();
+        EXPECT_EQ(r.slug, "validation") << body.dump();
+    }
+}
+
+TEST(IndexRequest, EmptyFieldNameIsRejected) {
+    Refusal r = refusalFrom([]{ parseIndexRequest(json{{"field", ""}}); });
+    EXPECT_EQ(r.slug, "validation");
+}
+
+TEST(IndexRequest, CompositeIsUniqueAndKeepsFieldOrder) {
+    IndexRequest r = parseIndexRequest(json{{"fields", {"chat_id", "file_unique_id"}}});
+    EXPECT_TRUE(r.composite());
+    EXPECT_TRUE(r.field.empty());
+    EXPECT_TRUE(r.unique);
+    ASSERT_EQ(r.fields.size(), 2u);
+    EXPECT_EQ(r.fields[0], "chat_id");
+    EXPECT_EQ(r.fields[1], "file_unique_id");
+}
+
+TEST(IndexRequest, CompositeAcceptsExplicitUniqueTrue) {
+    IndexRequest r = parseIndexRequest(json{{"fields", {"a", "b"}}, {"unique", true}});
+    EXPECT_TRUE(r.composite());
+    EXPECT_TRUE(r.unique);
+}
+
+// `unique: null` is "I did not set this", which is the same as omitting it.
+TEST(IndexRequest, CompositeAcceptsNullUnique) {
+    IndexRequest r = parseIndexRequest(json{{"fields", {"a", "b"}}, {"unique", nullptr}});
+    EXPECT_TRUE(r.unique);
+}
+
+TEST(IndexRequest, CompositeRefusesExplicitUniqueFalse) {
+    Refusal r = refusalFrom([]{
+        parseIndexRequest(json{{"fields", {"a", "b"}}, {"unique", false}});
+    });
+    EXPECT_EQ(r.code, ErrCode::Unprocessable);
+    EXPECT_EQ(r.slug, "validation");
+}
+
+// THE refusal: both spellings in one body. Asserted on the slug, because
+// `ambiguous_body` is what the document routes already answer for the same
+// class of mistake and a client should be able to branch on one slug.
+TEST(IndexRequest, FieldAndFieldsTogetherIsAmbiguous) {
+    Refusal r = refusalFrom([]{
+        parseIndexRequest(json{{"field", "a"}, {"fields", {"a", "b"}}});
+    });
+    EXPECT_EQ(r.code, ErrCode::Unprocessable);
+    EXPECT_EQ(r.slug, "ambiguous_body");
+}
+
+// Presence of both KEYS is the ambiguity, whatever the values: a caller sending
+// `field: null` alongside `fields` does not know which form it is sending, and
+// quietly taking `fields` would confirm a shape it never meant.
+TEST(IndexRequest, FieldAndFieldsTogetherIsAmbiguousEvenWhenOneIsNull) {
+    for (const json& body : {json{{"field", nullptr}, {"fields", {"a", "b"}}},
+                             json{{"field", "a"}, {"fields", json::array()}},
+                             json{{"field", ""}, {"fields", {"a", "b"}}}}) {
+        Refusal r = refusalFrom([&]{ parseIndexRequest(body); });
+        EXPECT_EQ(r.slug, "ambiguous_body") << body.dump();
+    }
+}
+
+TEST(IndexRequest, CompositeNeedsTwoFields) {
+    for (const json& fields : {json::array(), json::array({"only_one"})}) {
+        Refusal r = refusalFrom([&]{ parseIndexRequest(json{{"fields", fields}}); });
+        EXPECT_EQ(r.code, ErrCode::Unprocessable) << fields.dump();
+        EXPECT_EQ(r.slug, "validation") << fields.dump();
+    }
+}
+
+TEST(IndexRequest, CompositeRefusesRepeatedField) {
+    Refusal r = refusalFrom([]{ parseIndexRequest(json{{"fields", {"a", "b", "a"}}}); });
+    EXPECT_EQ(r.slug, "validation");
+}
+
+TEST(IndexRequest, CompositeRefusesNonStringEntries) {
+    Refusal r = refusalFrom([]{ parseIndexRequest(json{{"fields", {"a", 7}}}); });
+    EXPECT_EQ(r.slug, "validation");
+}
+
+TEST(IndexRequest, CompositeRefusesNonArrayFields) {
+    Refusal r = refusalFrom([]{ parseIndexRequest(json{{"fields", "a,b"}}); });
+    EXPECT_EQ(r.slug, "validation");
+}
+
+TEST(IndexRequest, CompositeRefusesEmptyAndMalformedPaths) {
+    for (const json& fields : {json::array({"a", ""}),
+                               json::array({"a", ".b"}),
+                               json::array({"a", "b."}),
+                               json::array({"a", "b..c"})}) {
+        Refusal r = refusalFrom([&]{ parseIndexRequest(json{{"fields", fields}}); });
+        EXPECT_EQ(r.slug, "validation") << fields.dump();
+    }
+}
+
+// A dotted path IS legal - it addresses a nested field.
+TEST(IndexRequest, CompositeAcceptsDottedPaths) {
+    IndexRequest r = parseIndexRequest(json{{"fields", {"chat.id", "file.unique_id"}}});
+    ASSERT_EQ(r.fields.size(), 2u);
+    EXPECT_EQ(r.fields[0], "chat.id");
+}
+
+TEST(CompositeFieldsParam, TwoOrMoreFieldsPass) {
+    auto f = parseCompositeFieldsParam({"chat_id", "file_unique_id"});
+    ASSERT_EQ(f.size(), 2u);
+    EXPECT_EQ(f[1], "file_unique_id");
+}
+
+// An empty `fields` must never mean "drop every constraint": it is the shape a
+// client sends when its query-string building went wrong.
+TEST(CompositeFieldsParam, EmptyIsRejected) {
+    Refusal r = refusalFrom([]{ parseCompositeFieldsParam({}); });
+    EXPECT_EQ(r.code, ErrCode::Unprocessable);
+    EXPECT_EQ(r.slug, "validation");
+}
+
+TEST(CompositeFieldsParam, SingleFieldIsRejected) {
+    Refusal r = refusalFrom([]{ parseCompositeFieldsParam({"chat_id"}); });
+    EXPECT_EQ(r.slug, "validation");
+}
+
+TEST(CompositeFieldsParam, RepeatedFieldIsRejected) {
+    Refusal r = refusalFrom([]{ parseCompositeFieldsParam({"a", "a"}); });
+    EXPECT_EQ(r.slug, "validation");
+}