Parcourir la source

feat(functions): cron, database events, and a job queue

Functions can now be triggered by a schedule, by a database change, or by
being enqueued - not only by an HTTP request.

The scheduler and the event watcher live in vectorapi because there must
be exactly ONE of each; N runners each firing every cron is the obvious
bug. Runners claim from a single global queue with a compare-and-set, so
two runners cannot both run one job, and a claim that goes stale returns
to pending - which is how work survives the runner that was going to do
it dying mid-job.

Cron honours an IANA `tz`, which used to be accepted and silently
dropped. 08:00 in Budapest is 06:00 UTC in winter and 07:00 in summer, so
a schedule without a zone drifts by an hour twice a year - the kind of
bug nobody notices for five months. Both DST discontinuities are decided
deliberately rather than left to the library: a SKIPPED local time still
fires once, at the moment the gap ends, and a REPEATED one fires once,
not twice. An unknown zone is refused on push, not at the first fire.

The cron grammar now has ONE implementation. descriptor.cpp carried its
own shape-only parser; a schedule that validated on push and then never
matched would have looked exactly like a broken scheduler. The
replacement was checked against the deleted parser over 4165 generated
expressions, zero divergence.

The loop guard reads provenance from the event's own actor (client
2.12.0). A function that writes to a table it watches re-triggers itself,
so every write a function makes is stamped `fn:<project>/<id>:<depth>`
and a chain is refused past a configured depth. This deliberately does
NOT put a marker in the user's documents, which would travel into every
export forever.

A job run gets its own wall-time ceiling (120 s) and its own pool lane.
One ceiling for everything meant no LLM call and no uncached embedding
could run server-side at all. The lane matters because a lease is held
for a run's whole duration: without it three slow jobs would leave one
runtime for every interactive route, and the second overlapping HTTP run
would block until vectorapi's read timeout fired - a 503 from a
perfectly healthy runner.

ctx gains jobs, crypto, time, binary-safe fetch, TTL and ifVersion.
ctx.time is NOT an Intl shim and does not pretend to be; what it omits
is written down.

Project secrets reach ctx.env without host access, stored encrypted in a
collection that is deliberately absent from the collection registry - so
even a function policy granting every collection cannot read them.

683 tests, all passing against client 2.12.0.
fszontagh il y a 1 mois
Parent
commit
4c4abccc92
73 fichiers modifiés avec 11653 ajouts et 356 suppressions
  1. 28 7
      api/llms.txt
  2. 272 14
      api/openapi.json
  3. 1 1
      packaging/Dockerfile.base
  4. 1 1
      packaging/build.sh
  5. 1 1
      packaging/deb/templates/control.runner
  6. 1 1
      packaging/deb/templates/control.server
  7. 3 3
      packaging/devstack/run-tests.sh
  8. 20 2
      runner/CMakeLists.txt
  9. 3 1
      runner/config/runner.json
  10. 60 1
      runner/include/runner/host_context.hpp
  11. 7 1
      runner/include/runner/js_runtime.hpp
  12. 7 1
      runner/src/function_env.cpp
  13. 32 7
      runner/src/function_env.hpp
  14. 876 12
      runner/src/host_context.cpp
  15. 383 26
      runner/src/host_prelude.js
  16. 473 0
      runner/src/job_worker.cpp
  17. 355 0
      runner/src/job_worker.hpp
  18. 228 14
      runner/src/main.cpp
  19. 103 15
      runner/src/run_service.cpp
  20. 61 5
      runner/src/run_service.hpp
  21. 62 0
      runner/tests/function_env_test.cpp
  22. 573 0
      runner/tests/host_context_test.cpp
  23. 522 0
      runner/tests/host_prelude_test.cpp
  24. 675 0
      runner/tests/job_worker_test.cpp
  25. 3 4
      runner/tests/js_runtime_test.cpp
  26. 267 1
      runner/tests/run_service_test.cpp
  27. 8 0
      src/CMakeLists.txt
  28. 19 1
      src/config.cpp
  29. 19 0
      src/config.hpp
  30. 70 12
      src/db_errors.cpp
  31. 9 0
      src/db_errors.hpp
  32. 123 0
      src/documents_util.hpp
  33. 361 0
      src/function_events.cpp
  34. 380 0
      src/function_events.hpp
  35. 328 0
      src/function_jobs.cpp
  36. 143 0
      src/function_jobs.hpp
  37. 262 0
      src/function_scheduler.cpp
  38. 180 0
      src/function_scheduler.hpp
  39. 441 0
      src/functions/cron.cpp
  40. 95 0
      src/functions/cron.hpp
  41. 32 133
      src/functions/descriptor.cpp
  42. 21 4
      src/functions/descriptor.hpp
  43. 188 0
      src/functions/timezone.cpp
  44. 60 0
      src/functions/timezone.hpp
  45. 132 0
      src/functions/wall_budget.hpp
  46. 212 71
      src/handlers/documents.cpp
  47. 139 0
      src/handlers/project_secrets.cpp
  48. 78 1
      src/handlers/project_settings.cpp
  49. 6 0
      src/handlers/projects.cpp
  50. 46 0
      src/main.cpp
  51. 80 0
      src/project_secret_store.cpp
  52. 64 0
      src/project_secret_store.hpp
  53. 28 0
      src/project_secrets.cpp
  54. 96 0
      src/project_secrets.hpp
  55. 13 0
      src/project_settings.cpp
  56. 22 1
      src/project_settings.hpp
  57. 11 6
      src/runner_client.hpp
  58. 1 0
      src/server.cpp
  59. 1 0
      src/server.hpp
  60. 1 1
      src/settings.cpp
  61. 1 2
      src/vector_search.cpp
  62. 1 1
      src/vector_search.hpp
  63. 68 1
      tests/CMakeLists.txt
  64. 304 0
      tests/test_api_integration.cpp
  65. 764 0
      tests/test_function_jobs.cpp
  66. 1 2
      tests/test_function_run_log.cpp
  67. 563 0
      tests/test_function_scheduler.cpp
  68. 680 0
      tests/test_functions_cron.cpp
  69. 252 0
      tests/test_functions_timezone.cpp
  70. 192 0
      tests/test_project_secret_store.cpp
  71. 94 0
      tests/test_project_secrets.cpp
  72. 46 0
      tests/test_project_settings.cpp
  73. 1 2
      tests/test_runner_client.cpp

+ 28 - 7
api/llms.txt

@@ -67,14 +67,16 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
 - `POST  /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` or `{...}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
 
-  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values` (the same slug `POST /indexes` returns). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
+  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values` (the same slug `POST /indexes` returns), and `error.details` names the index: `field`, the colliding `value` when that field is at the top level of the body you sent, and `conflicting_document_id` (the document already holding it). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
 
-  **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`.
-- `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID.
-- `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace a document (full upsert). Accepts the same two body shapes as POST.
-- `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (merge fields); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. 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".
+  **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields.
+- `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID. The body is the stored document **plus the database's read-only metadata**: `_id`, `_version` (an integer, starting at 1 and incremented by every write), `_created_at`, `_updated_at` (epoch ms), `_created_by`, `_updated_by`. `_version` is the value `?if_version=` takes, and it is also returned as an `ETag` header. These names are reserved: a field of your own called `_version` cannot be stored or read back.
+- `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace the document at `{id}`, **creating it when it does not exist** (a real upsert, as the method means). Accepts the same two body shapes as POST. **201** `{id, created:true, version:1}` with a `Location` header when it created, **200** `{id, created:false, version:N}` when it replaced. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection gets **403** on a PUT to an id that does not exist yet and can only replace. PUT does not take `?ttl_seconds=`; use POST with an `id` to create with an expiry.
+- `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (RFC 7396 merge: a `null` removes a field); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Returns `{id, version}`. **404** when the document does not exist - unlike PUT, PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
+
+  **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` and is not available on a `kind=vector` collection (**422** `conditional_unsupported` for both): the version-checked write has no expiry field, and it rewrites the whole document, which would drop the stored embedding.
 - `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.
+- `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).
 
 **Filter grammar**: `field:op:value`, repeatable and ANDed. On documents it is the `?filter=` query param; on vector search it is the `filters` body array. The same grammar, operators and semantics apply to both, because the database evaluates them.
@@ -143,6 +145,25 @@ Precedence for one embedding call: the collection's own `embedding_model` wins,
 - `PUT  /api/v1/projects/{project}/settings/embeddings` `{openai_api_base?, openai_api_key?, default_embedding_model?}` - Omit a field to leave it unchanged; send `null` to clear the override and inherit the global value. An empty string is rejected with **422**. Setting `openai_api_base` without an `openai_api_key` for the same project is rejected with **422** `embedding_base_requires_key`, so the global credential is never sent to a foreign endpoint. A project key without a project base URL is allowed (own key, default endpoint).
 - `DELETE /api/v1/projects/{project}/settings/embeddings` - Drop every override; the project inherits the global settings again.
 
+## Project secrets
+
+The values a project's functions read as `ctx.env.<NAME>` - a bot token, a provider key, a webhook signing secret. Stored per project in the database, so filling `ctx.env` no longer needs shell access to the runner host.
+
+A secret value is **write-only**: no endpoint ever returns it, masked or otherwise. A `GET` reports the name, whether a value is set, and the timestamps.
+
+Writes are **admin-only**, like a function's policy: the value is a live credential every function in the project then runs with, and an overwrite cannot be undone by inspection. Listing and reading the metadata only needs a key granted the project (capability-scoped publishable keys are refused), because an author has to know which names their code may read.
+
+A `NAME` must match `[A-Z_][A-Z0-9_]*` and be at most 64 characters - the charset a POSIX environment variable can carry, so a stored secret and a host variable can never hold one name under two spellings. A value is at most 8192 bytes, and a project may hold at most 64 secrets.
+
+**Precedence:** a host variable `SVAPI_FN_<project>__<NAME>` in `runner.env` wins over a stored secret of the same name. The host file can only be written by someone on the runner host, so it stays the override that a stolen API credential cannot shadow - and nothing changes for a deployment that already keeps its secrets there.
+
+- `GET    /api/v1/projects/{project}/secrets` - `{project, secrets:[{name, set, created_at, updated_at}], count, max_secrets, max_value_bytes}`. Names only.
+- `GET    /api/v1/projects/{project}/secrets/{NAME}` - `{name, set, created_at, updated_at}`; **404** when the secret does not exist.
+- `PUT    /api/v1/projects/{project}/secrets/{NAME}` `{value}` - **admin only**. **201** on a first write, **200** on a rotation; the response never carries the value. **422** for a bad name, an empty or oversized value, or `secret_limit` when the project is already at 64 secrets.
+- `DELETE /api/v1/projects/{project}/secrets/{NAME}` - **admin only**. **404** when there was no such secret.
+
+Deleting a project deletes its secrets, so a recycled project name inherits nothing.
+
 ## Functions
 
 Server-side JavaScript that serves HTTP routes. These routes require a key granted the project (admin keys reach every project); capability-scoped publishable keys are refused. **Changing a function's policy is admin-only** - developers push code, admins grant what it may touch, exactly as keys already work.
@@ -171,7 +192,7 @@ export default async function (ctx) {
 - `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.
 - 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 the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). Never another project's, and never the runner's own configuration.
+- `ctx.env.<NAME>` - secrets for THIS project only, from two merged sources: the project's own secrets set over the API (see "Project secrets") and the runner's environment (`SVAPI_FN_<project>__<NAME>` in `runner.env`). A host variable wins over a stored secret of the same name. Never another project's, and never the runner's own configuration.
 - `ctx.log(...)` - captured into the run's `console`, bounded.
 
 **A denied collection access throws a catchable error** naming the collection and the operation, rather than returning an empty result - so a missing grant looks like a failure, not like missing data.

+ 272 - 14
api/openapi.json

@@ -141,6 +141,17 @@
           "out_of_memory": { "type": "boolean" }
         }
       },
+      "ProjectSecret": {
+        "type": "object",
+        "description": "One per-project function secret, as the API reports it. The value is write-only and never appears here, not masked and not as a length.",
+        "properties": {
+          "name": { "type": "string", "pattern": "^[A-Z_][A-Z0-9_]*$", "maxLength": 64 },
+          "set": { "type": "boolean", "description": "Whether a value is stored" },
+          "created_at": { "type": "integer", "description": "Unix seconds of the first write" },
+          "updated_at": { "type": "integer", "description": "Unix seconds of the last rotation" }
+        },
+        "required": ["name", "set"]
+      },
       "ProjectEmbeddingSettings": {
         "type": "object",
         "description": "Three views of a project's embedding configuration. In overrides, an empty string means the field is inherited.",
@@ -251,7 +262,7 @@
     },
     "responses": {
       "Conflict": {
-        "description": "Conflict. `error.code` distinguishes the two cases vectorapi returns 409 for: `duplicate_values` (a unique index was refused because the field already holds colliding values) and `relation_restricted` (a document delete was blocked by a restrict relation).",
+        "description": "Conflict. `error.code` distinguishes the cases vectorapi returns 409 for: `duplicate_values` (a unique index refused the write, or an index could not be declared because the field already holds colliding values), `relation_restricted` (a document delete was blocked by a restrict relation) and `version_conflict` (a conditional write with ?if_version= found the document at another version).",
         "content": {
           "application/json": {
             "schema": {
@@ -260,12 +271,17 @@
                 "error": {
                   "type": "object",
                   "properties": {
-                    "code": { "type": "string", "enum": ["duplicate_values", "relation_restricted"] },
+                    "code": { "type": "string", "enum": ["duplicate_values", "relation_restricted", "version_conflict"] },
                     "message": { "type": "string" },
                     "details": {
                       "type": "object",
-                      "description": "Machine-readable payload. For `duplicate_values`: `duplicate_examples` (array of up to five document ids, one per colliding value). For `relation_restricted`: `impacts` (array of the same shape returned by GET .../documents/{id}/delete-impact).",
+                      "description": "Machine-readable payload. For `duplicate_values` on a document write: `field` (which unique index refused it), `value` (the colliding value, present when that field is at the top level of the submitted body) and `conflicting_document_id` (the document already holding it); all three are omitted if the database's message cannot be parsed, so test for them rather than assuming. For `duplicate_values` from POST /indexes: `duplicate_examples` (array of up to five document ids, one per colliding value). For `relation_restricted`: `impacts` (array of the same shape returned by GET .../documents/{id}/delete-impact). For `version_conflict`: `expected_version` and, when it could be read back, `current_version`.",
                       "properties": {
+                        "field": { "type": "string" },
+                        "value": { "description": "The colliding value, as submitted. Any JSON type." },
+                        "conflicting_document_id": { "type": "string" },
+                        "expected_version": { "type": "integer" },
+                        "current_version": { "type": "integer" },
                         "duplicate_examples": { "type": "array", "items": { "type": "string" } },
                         "impacts": {
                           "type": "array",
@@ -719,7 +735,11 @@
                 "schema": {
                   "type": "object",
                   "properties": {
-                    "documents": { "type": "array", "items": { "type": "object" } },
+                    "documents": {
+                      "type": "array",
+                      "description": "Each row is the stored document plus the database's read-only metadata (_id, _version, _created_at, _updated_at, _created_by, _updated_by), the same shape a single GET returns. _version makes a filtered listing a usable starting point for a conditional write (?if_version=) without a second request per row.",
+                      "items": { "type": "object" }
+                    },
                     "count": { "type": "integer" }
                   }
                 }
@@ -757,7 +777,7 @@
             "application/json": {
               "schema": {
                 "type": "object",
-                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. `id` here is the document id, not a field, and is stripped from what is stored.",
+                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. `id` here is the document id, not a field, and is stripped from what is stored. The database's metadata fields (_id, _version, _created_at, _updated_at, _created_by, _updated_by) are stripped too, so a document read, edited and sent straight back does not store stale metadata as real fields.",
                 "properties": {
                   "id": {
                     "type": "string",
@@ -789,6 +809,7 @@
           "401": { "description": "Unauthorized" },
           "403": { "description": "Forbidden" },
           "404": { "description": "Collection not found" },
+          "409": { "$ref": "#/components/responses/Conflict" },
           "422": { "description": "Validation error" },
           "429": { "description": "Too Many Requests (rate-limited scoped key)" }
         }
@@ -820,13 +841,31 @@
       ],
       "get": {
         "summary": "Get a document by ID",
+        "description": "Returns the stored document plus the database's read-only metadata. `_version` is the value ?if_version= takes on a conditional PUT or PATCH, so a read here is the first half of an optimistic-concurrency round trip; it is also returned as an ETag header.",
         "operationId": "getDocument",
         "responses": {
           "200": {
             "description": "Document",
+            "headers": {
+              "ETag": {
+                "description": "The document's `_version`, quoted (e.g. \"7\"). Informational: conditional writes take the number in the ?if_version= query parameter, not an If-Match header.",
+                "schema": { "type": "string" }
+              }
+            },
             "content": {
               "application/json": {
-                "schema": { "type": "object" }
+                "schema": {
+                  "type": "object",
+                  "description": "The stored document's own fields, plus the metadata below. These six names are reserved by the database: a field of your own called _version can neither be stored nor read back.",
+                  "properties": {
+                    "_id": { "type": "string", "description": "The document id, the same value as in the path." },
+                    "_version": { "type": "integer", "description": "Starts at 1 and is incremented by every write. The value to send as ?if_version= on a conditional write." },
+                    "_created_at": { "type": "integer", "description": "Epoch milliseconds." },
+                    "_updated_at": { "type": "integer", "description": "Epoch milliseconds." },
+                    "_created_by": { "type": "string" },
+                    "_updated_by": { "type": "string" }
+                  }
+                }
               }
             }
           },
@@ -837,32 +876,83 @@
         }
       },
       "put": {
-        "summary": "Replace a document (full upsert by ID)",
+        "summary": "Replace a document by ID, creating it when absent (upsert)",
+        "description": "PUT stores the document at the id in the path whether or not it already exists, which is what the method means and what lets a client key records by an id it receives from elsewhere (an external call id, say) without probing first. A replace is not a merge: fields the body omits are dropped. Creating counts as an insert for authorization, so a capability-scoped key granted `update` but not `insert` on the collection may only replace and gets 403 on an id that does not exist yet. PATCH, unlike PUT, never creates. PUT takes no ttl_seconds: create with an expiry via POST with an `id`.",
         "operationId": "replaceDocument",
+        "parameters": [
+          {
+            "name": "if_version",
+            "in": "query",
+            "required": false,
+            "schema": { "type": "integer", "minimum": 1 },
+            "description": "Conditional write: apply only if the document is still at this version (read it as `_version` from a GET or a listing). On a mismatch the write is refused with 409 version_conflict and error.details.expected_version / current_version. Must be a positive integer - versions start at 1, so 0 is rejected with 422 rather than read as \"must not exist\". A conditional write never creates: if_version against an absent document is 404."
+          }
+        ],
         "requestBody": {
           "required": true,
           "content": {
             "application/json": {
               "schema": {
                 "type": "object",
-                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. An `id` in the body is ignored: the URL supplies it."
+                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. An `id` in the body is ignored: the URL supplies it. The database's metadata fields (_id, _version, _created_at, _updated_at, _created_by, _updated_by) are stripped, so a document read and sent straight back does not store stale metadata as real fields."
               }
             }
           }
         },
         "responses": {
-          "200": { "description": "Document replaced" },
+          "200": {
+            "description": "Document replaced",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "id": { "type": "string" },
+                    "created": { "type": "boolean", "description": "false on this status." },
+                    "version": { "type": "integer", "description": "The document's version after this write." }
+                  }
+                }
+              }
+            }
+          },
+          "201": {
+            "description": "Document created at the given id",
+            "headers": {
+              "Location": { "description": "The document's URL, the same as the request target.", "schema": { "type": "string" } }
+            },
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "id": { "type": "string" },
+                    "created": { "type": "boolean", "description": "true on this status." },
+                    "version": { "type": "integer", "description": "1: a newly created document." }
+                  }
+                }
+              }
+            }
+          },
           "401": { "description": "Unauthorized" },
-          "403": { "description": "Forbidden" },
-          "404": { "description": "Collection not found" },
+          "403": { "description": "Forbidden (including a scope that permits update but not insert, on a PUT that would create)" },
+          "404": { "description": "Collection not found, or ?if_version= was sent for a document that does not exist" },
+          "409": { "$ref": "#/components/responses/Conflict" },
           "422": { "description": "Validation error" },
           "429": { "description": "Too Many Requests (rate-limited scoped key)" }
         }
       },
       "patch": {
         "summary": "Partially update a document (merge fields)",
+        "description": "An RFC 7396 merge patch: the fields in the body are merged into the stored document and a null removes a field. 404 when the document does not exist - PATCH never creates, because merging fields into nothing has no defined result and a patch body is not a whole document. Use PUT to create.",
         "operationId": "patchDocument",
         "parameters": [
+          {
+            "name": "if_version",
+            "in": "query",
+            "required": false,
+            "schema": { "type": "integer", "minimum": 1 },
+            "description": "Conditional write: merge only if the document is still at this version (read it as `_version` from a GET or a listing). On a mismatch: 409 version_conflict with error.details.expected_version / current_version. Must be a positive integer (422 otherwise). Two combinations are refused with 422 conditional_unsupported rather than approximated: together with ttl_seconds (a version-checked write carries no expiry), and on a kind=vector collection (it rewrites the whole document, which would drop the stored embedding)."
+          },
           {
             "name": "ttl_seconds",
             "in": "query",
@@ -877,17 +967,31 @@
             "application/json": {
               "schema": {
                 "type": "object",
-                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. PATCH merges the fields INSIDE the wrapper, not a field called `data`. An `id` in the body is ignored: the URL supplies it."
+                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. PATCH merges the fields INSIDE the wrapper, not a field called `data`. An `id` in the body is ignored: the URL supplies it. The database's metadata fields (_id, _version, _created_at, _updated_at, _created_by, _updated_by) are stripped."
               }
             }
           }
         },
         "responses": {
-          "200": { "description": "Document updated" },
+          "200": {
+            "description": "Document updated",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "id": { "type": "string" },
+                    "version": { "type": "integer", "description": "The document's version after this write." }
+                  }
+                }
+              }
+            }
+          },
           "401": { "description": "Unauthorized" },
           "403": { "description": "Forbidden" },
           "404": { "description": "Document not found" },
-          "422": { "description": "Validation error" },
+          "409": { "$ref": "#/components/responses/Conflict" },
+          "422": { "description": "Validation error, including conditional_unsupported for if_version with ttl_seconds or on a vector collection" },
           "429": { "description": "Too Many Requests (rate-limited scoped key)" }
         }
       },
@@ -1657,6 +1761,160 @@
         }
       }
     },
+    "/api/v1/projects/{project}/secrets": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        }
+      ],
+      "get": {
+        "summary": "List this project's function secrets by name. Values are never returned - only the name, whether a value is set, and the timestamps.",
+        "description": "Project-manage: a function author needs to know which names their code may read as ctx.env.<NAME>.",
+        "operationId": "listProjectSecrets",
+        "responses": {
+          "200": {
+            "description": "Secret names",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "project": { "type": "string" },
+                    "secrets": {
+                      "type": "array",
+                      "items": { "$ref": "#/components/schemas/ProjectSecret" }
+                    },
+                    "count": { "type": "integer" },
+                    "max_secrets": { "type": "integer" },
+                    "max_value_bytes": { "type": "integer" }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such project" }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/secrets/{name}": {
+      "parameters": [
+        {
+          "name": "project",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string" },
+          "description": "Project name"
+        },
+        {
+          "name": "name",
+          "in": "path",
+          "required": true,
+          "schema": { "type": "string", "pattern": "^[A-Z_][A-Z0-9_]*$", "maxLength": 64 },
+          "description": "Secret name, an environment-variable-style identifier. Reaches the project's functions as ctx.env.<NAME>."
+        }
+      ],
+      "get": {
+        "summary": "Whether this secret is set. The value is never returned by any endpoint.",
+        "operationId": "getProjectSecret",
+        "responses": {
+          "200": {
+            "description": "Secret metadata",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/ProjectSecret" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - requires a key granted this project; capability-scoped keys are refused" },
+          "404": { "description": "No such project or secret" },
+          "422": { "description": "Invalid secret name" }
+        }
+      },
+      "put": {
+        "summary": "Set or rotate one secret (admin only). Write-only: the value is never readable again.",
+        "description": "The value reaches this project's functions as ctx.env.<NAME>. A host variable SVAPI_FN_<project>__<NAME> in the runner's environment takes precedence over the stored value of the same name.",
+        "operationId": "putProjectSecret",
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "required": ["value"],
+                "properties": {
+                  "value": {
+                    "type": "string",
+                    "minLength": 1,
+                    "maxLength": 8192,
+                    "description": "Write-only, never returned. Empty is rejected; DELETE the secret to remove it."
+                  }
+                }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Secret rotated",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/ProjectSecret" }
+              }
+            }
+          },
+          "201": {
+            "description": "Secret created",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/ProjectSecret" }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - admin only" },
+          "404": { "description": "No such project" },
+          "422": {
+            "description": "Validation failed: bad name, empty or oversized value, or the project is at its secret limit (code secret_limit)",
+            "content": {
+              "application/json": {
+                "schema": { "$ref": "#/components/schemas/Error" }
+              }
+            }
+          }
+        }
+      },
+      "delete": {
+        "summary": "Delete one secret (admin only)",
+        "operationId": "deleteProjectSecret",
+        "responses": {
+          "200": {
+            "description": "Secret deleted",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "deleted": { "type": "string" },
+                    "project": { "type": "string" }
+                  }
+                }
+              }
+            }
+          },
+          "401": { "description": "Unauthorized" },
+          "403": { "description": "Forbidden - admin only" },
+          "404": { "description": "No such project or secret" },
+          "422": { "description": "Invalid secret name" }
+        }
+      }
+    },
     "/fn/{project}/{path}": {
       "description": "Public dispatch for a project's HTTP functions. Unauthenticated by design: a published function's route is public. The project is the first path segment; the remainder is matched against that project's declared routes.",
       "get":    { "$ref": "#/components/pathItems/FunctionDispatch/get" },

+ 1 - 1
packaging/Dockerfile.base

@@ -28,7 +28,7 @@ RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
 # only segfaults on the next service restart. Keep this equal to the client
 # version installed on the deploy target; when the target's DB moves, bump this
 # and ship both together.
-ARG DB_CLIENT_VERSION=2.11.4-1
+ARG DB_CLIENT_VERSION=2.12.0-1
 
 # Publishing a new client re-indexes the apt pool, so the pinned version is
 # often no longer installable from the repo. build.sh copies the matching .debs

+ 1 - 1
packaging/build.sh

@@ -21,7 +21,7 @@ BASE_IMAGE_NAME="smartbotic-vectorapi-build-base:debian13"
 # Client version the server deb is compiled against. Must equal the version
 # installed on the deploy target: every 2.x client shares one SONAME, so a
 # mismatch installs cleanly and only segfaults on the next service restart.
-DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.11.4-1}"
+DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.12.0-1}"
 BUILD_JOBS="${BUILD_JOBS:-$(nproc)}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
 

+ 1 - 1
packaging/deb/templates/control.runner

@@ -12,7 +12,7 @@ Description: Smartbotic VectorAPI - server-side function runner
 Homepage: https://smartbotics.ai
 Section: contrib/utils
 Priority: optional
-Depends: libsmartbotic-db-client (>= 2.11.4), libssl3t64, libsystemd0, libspdlog1.15
+Depends: libsmartbotic-db-client (>= 2.12.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata
 Recommends: smartbotic-vectorapi (= {{VERSION}})
 Breaks: smartbotic-vectorapi (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 1 - 1
packaging/deb/templates/control.server

@@ -10,7 +10,7 @@ Description: Smartbotic VectorAPI — REST API for RAG vectors and JSON
 Homepage: https://smartbotics.ai
 Section: contrib/utils
 Priority: optional
-Depends: libsmartbotic-db-client (>= 2.3.0), libssl3t64, libsystemd0, libspdlog1.15
+Depends: libsmartbotic-db-client (>= 2.12.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata
 Recommends: smartbotic-vectorapi-webui (= {{VERSION}})
 Breaks: smartbotic-vectorapi-runner (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 3 - 3
packaging/devstack/run-tests.sh

@@ -14,11 +14,11 @@ set -euo pipefail
 REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
 BASE_IMAGE="${BASE_IMAGE:-smartbotic-vectorapi-build-base:debian13}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
-DB_DEB="${DB_DEB:-$DEB_REPO_DIR/dist/smartbotic-database_2.11.4-1_amd64.deb}"
+DB_DEB="${DB_DEB:-$DEB_REPO_DIR/dist/smartbotic-database_2.12.0-1_amd64.deb}"
 # The base image pins a client version; tests must compile against the same one
 # the release does, so the dev package is installed here rather than assumed.
-CLIENT_DEV_DEB="${CLIENT_DEV_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client-dev_2.11.4-1_amd64.deb}"
-CLIENT_DEB="${CLIENT_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client_2.11.4-1_amd64.deb}"
+CLIENT_DEV_DEB="${CLIENT_DEV_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client-dev_2.12.0-1_amd64.deb}"
+CLIENT_DEB="${CLIENT_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client_2.12.0-1_amd64.deb}"
 FILTER="${1:-}"
 # BUILD_RUNNER=ON also builds and tests the QuickJS runner. Off by default
 # because it vendors QuickJS from GitHub at configure time.

+ 20 - 2
runner/CMakeLists.txt

@@ -86,11 +86,17 @@ set(SVAPI_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../src")
 add_library(runner_protocol STATIC
     src/run_service.cpp
     src/function_env.cpp
-    src/runner_auth.cpp)
+    src/runner_auth.cpp
+    src/job_worker.cpp
+    ${SVAPI_SRC_DIR}/functions/timezone.cpp)
 target_include_directories(runner_protocol PUBLIC
     ${CMAKE_CURRENT_SOURCE_DIR}/src
     ${SVAPI_SRC_DIR})
-target_link_libraries(runner_protocol PUBLIC runner_core nlohmann_json::nlohmann_json)
+if(NOT TARGET spdlog::spdlog)
+    find_package(spdlog REQUIRED)   # the job worker logs
+endif()
+target_link_libraries(runner_protocol PUBLIC
+    runner_core nlohmann_json::nlohmann_json spdlog::spdlog)
 target_compile_features(runner_protocol PUBLIC cxx_std_20)
 set_target_properties(runner_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)
 
@@ -123,11 +129,23 @@ if(BUILD_TESTS)
     add_executable(test_run_service
         tests/run_service_test.cpp
         ${SVAPI_SRC_DIR}/functions/descriptor.cpp
+        ${SVAPI_SRC_DIR}/functions/cron.cpp
         ${SVAPI_SRC_DIR}/apikey.cpp)
     target_link_libraries(test_run_service PRIVATE
         runner_protocol OpenSSL::Crypto GTest::gtest_main)
     gtest_discover_tests(test_run_service PROPERTIES TIMEOUT 120)
 
+    # The job worker's decisions - retry classification, backoff, the trigger
+    # mapping - driven against a fake queue and a real engine.
+    add_executable(test_job_worker
+        tests/job_worker_test.cpp
+        ${SVAPI_SRC_DIR}/functions/descriptor.cpp
+        ${SVAPI_SRC_DIR}/functions/cron.cpp
+        ${SVAPI_SRC_DIR}/apikey.cpp)
+    target_link_libraries(test_job_worker PRIVATE
+        runner_protocol OpenSSL::Crypto GTest::gtest_main)
+    gtest_discover_tests(test_job_worker 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

+ 3 - 1
runner/config/runner.json

@@ -5,8 +5,10 @@
   "runtime": {
     "pool_size": 4,
     "memory_limit_bytes": 134217728,
-    "max_wall_time_ms": 2000,
+    "max_http_wall_time_ms": 2000,
+    "max_job_wall_time_ms": 120000,
     "default_wall_time_ms": 0,
+    "project_budget_ttl_sec": 15,
     "max_stack_bytes": 524288,
     "bytecode_cache_entries": 64
   }

+ 60 - 1
runner/include/runner/host_context.hpp

@@ -24,6 +24,45 @@
 ///      drift apart, which is the whole reason Principal exists.
 namespace svapi::runner {
 
+/// What `ctx.jobs` needs from the job queue.
+///
+/// A PORT rather than a FunctionJobQueue, for the same two reasons job_worker.hpp
+/// has one. The queue includes db_gateway.hpp and therefore the database client,
+/// which does not compile everywhere this does; and the rules worth testing here
+/// (own project only, depth bounded, a dedupe key means one job) are decided
+/// before the queue is reached, so the tests must be able to drive the decision
+/// without a database behind it.
+///
+/// An implementation MUST refuse a function the caller could not otherwise
+/// reach: the same check `/fn/{project}/*` makes, which is that the target is a
+/// function of THIS project that is enabled and valid. A disabled or unknown
+/// function is absent, not forbidden - the enqueue fails with `not_found` rather
+/// than telling a script which function ids exist.
+class JobPort {
+public:
+    virtual ~JobPort() = default;
+
+    /// Enqueue one job. `project` is always the enqueuing function's own
+    /// project; it is passed rather than implied so the contract is explicit
+    /// and a test can assert it.
+    ///
+    /// `jobId` empty means "mint one"; non-empty is a DETERMINISTIC id derived
+    /// from a dedupe key, and the queue stores by id, so enqueuing the same key
+    /// twice has to leave exactly one job.
+    ///
+    /// `trigger` is the whole `ctx` trigger object the run will receive, not
+    /// just the caller's payload - the run reads `ctx.body` out of it.
+    ///
+    /// Returns the job id. Throws ApiError to refuse.
+    virtual std::string enqueue(const std::string& project, const std::string& functionId,
+                                const nlohmann::json& trigger, uint64_t runAfterEpochSec,
+                                uint32_t depth, const std::string& jobId) = 0;
+
+    /// Cancel a job of `project`. False when there was nothing to cancel (no
+    /// such job, or it has already been claimed and may be running right now).
+    virtual bool cancel(const std::string& project, const std::string& jobId) = 0;
+};
+
 /// Everything one run needs from the server. Built by the runner from the
 /// function's registry row plus the incoming trigger; never from the script.
 struct HostContextConfig {
@@ -48,6 +87,25 @@ struct HostContextConfig {
     /// rather than throwing, so "no database" has to mean "do not read one",
     /// not "handle the error".
     std::shared_ptr<const functions::SsrfPolicy> egressPolicy;
+
+    /// Where ctx.jobs.enqueue goes. NULL means functions cannot enqueue, and
+    /// ctx.jobs.enqueue refuses with `jobs_unavailable` - the same posture as a
+    /// runner installed with no endpoints configured: a capability that was
+    /// never wired fails loudly rather than looking like it worked.
+    std::shared_ptr<JobPort> jobs;
+
+    /// How many triggers deep the run that is calling ctx.jobs already is.
+    ///
+    /// Falls back to `trigger["depth"]` when left at 0, so it holds whether the
+    /// job worker threads the depth through this field or through the trigger it
+    /// stored. Either way the enqueued job gets depth + 1.
+    uint32_t jobDepth = 0;
+
+    /// The deepest chain ctx.jobs.enqueue will extend. A function that enqueues
+    /// itself - directly, or through two functions that enqueue each other -
+    /// would otherwise run forever, and the cost is paid by every other tenant
+    /// sharing the runners.
+    uint32_t maxJobDepth = 8;
 };
 
 /// Installs `ctx` for one run. One instance per run: it holds that run's
@@ -76,7 +134,8 @@ private:
 };
 
 /// The JavaScript prelude evaluated before the user module, which turns the few
-/// native bindings (`__hostDb`, `__hostFetch`, `__hostLog`) into the chainable
+/// native bindings (`__hostDb`, `__hostFetch`, `__hostLog`, `__hostJobs`,
+/// `__hostCrypto`, `__hostTime`) into the chainable
 /// builder the design document specifies. Kept in JS because a fluent builder is
 /// natural there and miserable in C++; kept SMALL because everything it does not
 /// do is done in C++ where it can be tested without an engine.

+ 7 - 1
runner/include/runner/js_runtime.hpp

@@ -21,8 +21,14 @@
 /// still include this header if it ever needed the types.
 namespace svapi::runner {
 
-/// Per-run ceilings. `wall_time_ms` is the configured maximum, not a default a
+/// Per-run ceilings. `wall_time_ms` is the HARD maximum, not a default a
 /// descriptor can raise: run()'s override is clamped to it.
+///
+/// The engine knows one ceiling and should: a budget is a policy decision, and
+/// the policy has more inputs than the engine can see (how the run was
+/// triggered, the project's maximum). RunService resolves those into a single
+/// override and sets this to the largest budget it will ever grant, so the
+/// clamp here is a backstop rather than the thing that decides.
 struct JsLimits {
     size_t memory_limit_bytes = 128u * 1024 * 1024;
     int64_t wall_time_ms = 2000;

+ 7 - 1
runner/src/function_env.cpp

@@ -1,4 +1,5 @@
 #include "function_env.hpp"
+#include "project_secrets.hpp"
 #include <cstring>
 
 extern char** environ;
@@ -6,8 +7,13 @@ extern char** environ;
 namespace svapi::runner {
 
 nlohmann::json functionEnvFor(const std::string& project,
-                              const std::vector<std::string>& environment) {
+                              const std::vector<std::string>& environment,
+                              const std::map<std::string, std::string>& storedSecrets) {
     nlohmann::json out = nlohmann::json::object();
+    // Stored secrets first, so the host loop below overwrites them: the host
+    // file is the channel that cannot be reached remotely, and it wins.
+    for (const auto& [name, value] : storedSecrets)
+        if (svapi::validSecretName(name)) out[name] = value;
     const std::string prefix = std::string(kFunctionEnvPrefix) + project + "__";
     for (const std::string& entry : environment) {
         const std::size_t eq = entry.find('=');

+ 32 - 7
runner/src/function_env.hpp

@@ -1,4 +1,5 @@
 #pragma once
+#include <map>
 #include <nlohmann/json.hpp>
 #include <string>
 #include <vector>
@@ -10,10 +11,32 @@ constexpr const char* kFunctionEnvPrefix = "SVAPI_FN_";
 
 /// The secrets one project's functions may read, as `ctx.env`.
 ///
-/// Secrets live in the runner's own environment, which systemd loads from
-/// /etc/smartbotic-vectorapi/runner.env - a file an operator can lock down,
-/// rather than the settings document, which every project-manage caller can
-/// read back over the API.
+/// There are two sources, merged here:
+///
+///   1. `storedSecrets` - the project's own secrets, written over the API
+///      (admin-only) and held per project in the database. This is the source a
+///      project can manage without shell access to the runner host, which is
+///      the whole point of it existing.
+///   2. the runner's own environment, which systemd loads from
+///      /etc/smartbotic-vectorapi/runner.env - a file only someone with access
+///      to the host can edit.
+///
+/// PRECEDENCE: the host environment WINS over a stored secret of the same name.
+/// Two reasons, and both matter more than "newest write wins":
+///   - runner.env is the channel that cannot be reached remotely. An API
+///     credential can be stolen; a file on the runner host cannot be written
+///     without being on that host. The operator therefore keeps an override
+///     that no API caller can shadow, which is what makes it usable as the
+///     break-glass fix when a stored secret is wrong or hostile.
+///   - it is the direction that cannot change behaviour under an existing
+///     deployment: every secret in a running installation is a host variable
+///     today, so the merge leaves all of them exactly as they were, and a
+///     stored secret can only ever fill a name the host does not define.
+///
+/// A stored name is re-checked against validSecretName() here rather than
+/// trusted: the API validates on write, but a row hand-written straight into
+/// the collection must not be able to put an arbitrary key - `__proto__`, say -
+/// into the object a script sees as `ctx.env`.
 ///
 /// A variable is named `SVAPI_FN_<project>__<NAME>` and reaches the function as
 /// `ctx.env.<NAME>`. The project is part of the NAME on purpose: one runner
@@ -27,10 +50,12 @@ constexpr const char* kFunctionEnvPrefix = "SVAPI_FN_";
 /// contains `__` cannot carry secrets; that is documented rather than guarded,
 /// because the alternative encodings all have a worse ambiguity somewhere.
 ///
-/// Pure: takes the environment as "NAME=VALUE" strings so the mapping is
-/// testable without touching the process environment.
+/// Pure: takes the environment as "NAME=VALUE" strings, and the project's
+/// stored secrets as a plain map, so the whole mapping is testable without
+/// touching the process environment or a database.
 nlohmann::json functionEnvFor(const std::string& project,
-                              const std::vector<std::string>& environment);
+                              const std::vector<std::string>& environment,
+                              const std::map<std::string, std::string>& storedSecrets = {});
 
 /// The current process environment as "NAME=VALUE" strings.
 std::vector<std::string> processEnvironment();

Fichier diff supprimé car celui-ci est trop grand
+ 876 - 12
runner/src/host_context.cpp


+ 383 - 26
runner/src/host_prelude.js

@@ -15,11 +15,96 @@
 // Host calls are SYNCHRONOUS. The design relies on `await` of a non-promise
 // being a no-op, which is why nothing here returns a promise: a sync host call
 // cannot deadlock on a microtask queue the run may never drain.
-(function (ctx, __hostDb, __hostFetch, __hostLog) {
+//
+// Every refusal raised here carries a `code`, for the same reason the native
+// side attaches one to an ApiError: a script branches on `e.code`, and matching
+// message text is how a function breaks on a reworded sentence.
+(function (ctx, __hostDb, __hostFetch, __hostLog, __hostJobs, __hostCrypto, __hostTime) {
   'use strict';
 
-  function need(cond, message) {
-    if (!cond) throw new TypeError(message);
+  function fail(code, message) {
+    const e = new TypeError(message);
+    e.code = code;
+    throw e;
+  }
+
+  function need(cond, message, code) {
+    if (!cond) fail(code === undefined ? 'validation' : code, message);
+  }
+
+  // A plain object, not an array, a Date, or null. Used wherever an "options
+  // bag" is accepted: passing an array would silently read nothing off it.
+  function isPlainObject(v) {
+    return v !== null && typeof v === 'object' && !Array.isArray(v);
+  }
+
+  function opts(v, what) {
+    if (v === undefined || v === null) return {};
+    need(isPlainObject(v), what + ' must be an object');
+    return v;
+  }
+
+  function nonNegativeInt(v, what) {
+    need(Number.isInteger(v) && v >= 0, what + ' must be a non-negative integer');
+    return v;
+  }
+
+  // Base64 is validated HERE, before any host call, so a typo in a signature or
+  // a truncated upload is a TypeError the author can read rather than a decode
+  // failure reported from the far side of the boundary. Standard alphabet only:
+  // the URL-safe variant decodes to different bytes, and silently accepting
+  // both would make `-` and `+` mean the same thing when they do not.
+  const kBase64 = /^[A-Za-z0-9+/]*={0,2}$/;
+  function base64String(v, what) {
+    need(typeof v === 'string', what + ' must be a base64 string');
+    need(v.length % 4 === 0 && kBase64.test(v), what + ' is not valid base64');
+    return v;
+  }
+
+  // A string, or { base64: '...' } for bytes that are not text. HMAC over a
+  // webhook body is the common case and that body is a string; a binary secret
+  // or a binary payload is the reason the second shape exists.
+  function bytesArg(v, what) {
+    if (typeof v === 'string') return { text: v };
+    need(isPlainObject(v) && typeof v.base64 === 'string',
+         what + " must be a string or { base64: '...' }");
+    return { base64: base64String(v.base64, what + '.base64') };
+  }
+
+  // --- write options ---------------------------------------------------------
+  //
+  // One reader for the three write calls, because `ttl_seconds` and `ifVersion`
+  // have to mean exactly the same thing on each of them. Absent is NOT zero:
+  // over HTTP, `?ttl_seconds=0` clears a document's expiry while omitting the
+  // parameter leaves it untouched, and collapsing the two here would make a
+  // plain `.patch()` quietly make a temporary document permanent.
+  function writeOptions(v, allowed, what) {
+    const o = opts(v, what + ' options');
+    const out = {};
+    for (const key in o) {
+      if (!Object.prototype.hasOwnProperty.call(o, key)) continue;
+      if (o[key] === undefined) continue;
+      need(allowed.indexOf(key) >= 0,
+           what + " does not take an option named '" + key + "'; it takes: " + allowed.join(', '));
+    }
+    if (o.ttl_seconds !== undefined && o.ttl_seconds !== null) {
+      out.ttl_seconds = nonNegativeInt(o.ttl_seconds, 'ttl_seconds');
+    }
+    if (o.ifVersion !== undefined && o.ifVersion !== null) {
+      // 0 is not a version any stored document has (the first write produces
+      // 1), so accepting it would be a precondition that can never hold.
+      need(Number.isInteger(o.ifVersion) && o.ifVersion > 0,
+           'ifVersion must be a positive integer, as returned in a document\'s _version');
+      out.ifVersion = o.ifVersion;
+    }
+    // Optimistic locking is a whole-document replace on the far side and that
+    // call carries no expiry argument, so the two cannot be honoured in one
+    // write. Refused rather than silently dropping the TTL, which would leave a
+    // document that was meant to expire living forever.
+    need(!(out.ttl_seconds !== undefined && out.ifVersion !== undefined),
+         'ttl_seconds and ifVersion cannot be combined; set the expiry in a separate call',
+         'unsupported_combination');
+    return out;
   }
 
   // A chained call returns a NEW ref: `ctx.collections('c')` is a value a
@@ -67,19 +152,24 @@
         need(typeof id === 'string' && id.length > 0, '.get() takes a document id');
         return __hostDb(name, 'get', { id: id });
       },
-      insert: function (doc) {
+      insert: function (doc, options) {
         need(doc !== null && typeof doc === 'object', '.insert() takes a document object');
-        return __hostDb(name, 'insert', { doc: doc });
+        const o = writeOptions(options, ['ttl_seconds'], '.insert()');
+        return __hostDb(name, 'insert', { doc: doc, ttl_seconds: o.ttl_seconds });
       },
-      update: function (id, doc) {
+      update: function (id, doc, options) {
         need(typeof id === 'string' && id.length > 0, '.update() takes a document id');
         need(doc !== null && typeof doc === 'object', '.update() takes a document object');
-        return __hostDb(name, 'update', { id: id, doc: doc });
+        const o = writeOptions(options, ['ttl_seconds', 'ifVersion'], '.update()');
+        return __hostDb(name, 'update', { id: id, doc: doc,
+                                          ttl_seconds: o.ttl_seconds, ifVersion: o.ifVersion });
       },
-      patch: function (id, fields) {
+      patch: function (id, fields, options) {
         need(typeof id === 'string' && id.length > 0, '.patch() takes a document id');
         need(fields !== null && typeof fields === 'object', '.patch() takes a fields object');
-        return __hostDb(name, 'patch', { id: id, doc: fields });
+        const o = writeOptions(options, ['ttl_seconds', 'ifVersion'], '.patch()');
+        return __hostDb(name, 'patch', { id: id, doc: fields,
+                                         ttl_seconds: o.ttl_seconds, ifVersion: o.ifVersion });
       },
       // Legal as a method name since ES5, and it is the name the design shows.
       delete: function (id) {
@@ -92,25 +182,34 @@
       // `.filter(...).search({...})` behaves the way the chain reads. An
       // explicit `filters` array in the argument is appended, not replaced:
       // dropping either set silently would widen the result.
-      search: function (opts) {
-        need(opts !== null && typeof opts === 'object', '.search() takes an options object');
-        const extra = opts.filters === undefined || opts.filters === null ? [] : opts.filters;
+      search: function (options) {
+        need(options !== null && typeof options === 'object', '.search() takes an options object');
+        const extra = options.filters === undefined || options.filters === null
+                      ? [] : options.filters;
         need(Array.isArray(extra), '.search() filters must be an array of strings');
         return __hostDb(name, 'search', {
-          query_text: opts.query_text,
-          query_vector: opts.query_vector,
-          top_k: opts.top_k,
-          min_score: opts.min_score,
+          query_text: options.query_text,
+          query_vector: options.query_vector,
+          top_k: options.top_k,
+          min_score: options.min_score,
           filters: query.filters.concat(extra)
         });
       },
-      store: function (opts) {
-        need(opts !== null && typeof opts === 'object', '.store() takes an options object');
+      store: function (options) {
+        need(options !== null && typeof options === 'object', '.store() takes an options object');
+        // A stored vector is an inserted document, so it takes the same expiry
+        // option an .insert() does - a cache of embeddings that cannot expire
+        // is a cache that grows forever.
+        let ttl;
+        if (options.ttl_seconds !== undefined && options.ttl_seconds !== null) {
+          ttl = nonNegativeInt(options.ttl_seconds, 'ttl_seconds');
+        }
         return __hostDb(name, 'store', {
-          text: opts.text,
-          vector: opts.vector,
-          metadata: opts.metadata,
-          id: opts.id
+          text: options.text,
+          vector: options.vector,
+          metadata: options.metadata,
+          id: options.id,
+          ttl_seconds: ttl
         });
       }
     };
@@ -123,23 +222,281 @@
     return ref(name, { filters: [], limit: 0, offset: 0, sort: '', desc: false });
   };
 
+  // --- ctx.fetch -------------------------------------------------------------
+
+  // A request body arrives in exactly one of three shapes, and never two.
+  // Reading `body` and ignoring a `bodyBase64` beside it would send the wrong
+  // bytes with no error anywhere, which is the same failure documentBody()
+  // refuses over HTTP with `ambiguous_body`.
+  const kMaxByteArray = 1024 * 1024;
+  function requestBody(o) {
+    const given = [];
+    if (o.body !== undefined && o.body !== null) given.push('body');
+    if (o.bodyBase64 !== undefined && o.bodyBase64 !== null) given.push('bodyBase64');
+    if (o.bodyBytes !== undefined && o.bodyBytes !== null) given.push('bodyBytes');
+    need(given.length <= 1,
+         'ctx.fetch() takes at most one of body, bodyBase64, bodyBytes; got ' + given.join(' and '),
+         'ambiguous_body');
+    if (given.length === 0) return {};
+
+    if (given[0] === 'body') {
+      need(typeof o.body === 'string',
+           'ctx.fetch() body must be a string; use bodyBase64 or bodyBytes for binary');
+      return { body: o.body };
+    }
+    if (given[0] === 'bodyBase64') {
+      return { bodyBase64: base64String(o.bodyBase64, 'ctx.fetch() bodyBase64') };
+    }
+
+    // A byte array is the convenient shape for a short payload a script built
+    // itself. It is capped because every element costs several bytes as JSON on
+    // the way to the host: base64 is roughly a quarter of the size, so a large
+    // payload is pointed at the shape that can carry it.
+    const bytes = o.bodyBytes;
+    need(Array.isArray(bytes), 'ctx.fetch() bodyBytes must be an array of byte values');
+    need(bytes.length <= kMaxByteArray,
+         'ctx.fetch() bodyBytes is limited to ' + kMaxByteArray +
+         ' entries; send a larger payload as bodyBase64',
+         'body_too_large');
+    for (let i = 0; i < bytes.length; i++) {
+      need(Number.isInteger(bytes[i]) && bytes[i] >= 0 && bytes[i] <= 255,
+           'ctx.fetch() bodyBytes[' + i + '] must be an integer between 0 and 255');
+    }
+    return { bodyBytes: bytes };
+  }
+
   ctx.fetch = function (url, options) {
     need(typeof url === 'string' && url.length > 0, 'ctx.fetch() takes a URL string');
-    const o = options === undefined || options === null ? {} : options;
-    need(typeof o === 'object', 'ctx.fetch() options must be an object');
+    const o = opts(options, 'ctx.fetch() options');
+
+    // 'text' is the default and behaves exactly as it always has. 'base64' is
+    // the only way a response that is not UTF-8 text can cross the boundary at
+    // all: the value handed to the engine is JSON, and JSON has no byte string,
+    // so an audio file or a PDF has to be encoded or refused.
+    const responseType = o.responseType === undefined || o.responseType === null
+                         ? 'text' : o.responseType;
+    need(responseType === 'text' || responseType === 'base64',
+         "ctx.fetch() responseType must be 'text' or 'base64'");
+
+    if (o.timeoutMs !== undefined && o.timeoutMs !== null) {
+      nonNegativeInt(o.timeoutMs, 'ctx.fetch() timeoutMs');
+    }
+    if (o.method !== undefined && o.method !== null) {
+      need(typeof o.method === 'string' && o.method.length > 0,
+           'ctx.fetch() method must be a string');
+    }
+    if (o.headers !== undefined && o.headers !== null) {
+      need(isPlainObject(o.headers), 'ctx.fetch() headers must be an object');
+    }
+    const body = requestBody(o);
+
     const res = __hostFetch(url, {
       method: o.method,
       headers: o.headers,
-      body: o.body,
+      body: body.body,
+      bodyBase64: body.bodyBase64,
+      bodyBytes: body.bodyBytes,
+      responseType: responseType,
       timeoutMs: o.timeoutMs
     });
+
     // `json()` is a method rather than an eagerly parsed field so a non-JSON
     // body is the caller's problem at the point they ask for it, not a failed
     // fetch of a response that arrived perfectly well.
-    res.json = function () { return JSON.parse(res.body); };
+    //
+    // On a base64 response it refuses instead of parsing: JSON.parse of base64
+    // would throw a SyntaxError about position 0, which tells the author
+    // nothing about the responseType they chose two lines earlier.
+    res.json = function () {
+      if (res.bodyEncoding === 'base64') {
+        fail('not_json',
+             "this response was fetched with responseType:'base64'; decode res.body yourself " +
+             "or refetch as text");
+      }
+      return JSON.parse(res.body);
+    };
     return res;
   };
 
+  // --- ctx.jobs --------------------------------------------------------------
+
+  const kMaxDedupeKey = 512;
+
+  ctx.jobs = {
+    // The project is NOT an argument. A function enqueues into its own project
+    // or not at all, and the host supplies the project from the registry row
+    // the run was built from - a project argument would be a tenancy boundary
+    // decided by the script.
+    enqueue: function (functionId, payload, options) {
+      need(typeof functionId === 'string' && functionId.length > 0,
+           'ctx.jobs.enqueue() takes a function id');
+      const o = opts(options, 'ctx.jobs.enqueue() options');
+      for (const key in o) {
+        if (!Object.prototype.hasOwnProperty.call(o, key)) continue;
+        if (o[key] === undefined) continue;
+        need(['runAt', 'delaySec', 'dedupeKey'].indexOf(key) >= 0,
+             "ctx.jobs.enqueue() does not take an option named '" + key +
+             "'; it takes: runAt, delaySec, dedupeKey");
+      }
+
+      const hasRunAt = o.runAt !== undefined && o.runAt !== null;
+      const hasDelay = o.delaySec !== undefined && o.delaySec !== null;
+      // Both would have to be reconciled, and any rule for that (earliest
+      // wins? last wins?) is a guess at what the author meant.
+      need(!(hasRunAt && hasDelay),
+           'ctx.jobs.enqueue() takes runAt or delaySec, not both',
+           'ambiguous_body');
+
+      let runAt;
+      if (hasRunAt) {
+        // A Date is accepted because it is what a script computing a time
+        // actually holds; everything else must be epoch milliseconds, the same
+        // unit Date.now() returns, so there is no ambiguity about seconds.
+        const ms = o.runAt instanceof Date ? o.runAt.getTime() : o.runAt;
+        need(typeof ms === 'number' && Number.isFinite(ms),
+             'ctx.jobs.enqueue() runAt must be a Date or epoch milliseconds');
+        // An Invalid Date yields NaN, which the check above already refuses.
+        need(ms >= 0, 'ctx.jobs.enqueue() runAt must not be before the epoch');
+        runAt = Math.floor(ms);
+      }
+      let delaySec;
+      if (hasDelay) delaySec = nonNegativeInt(o.delaySec, 'ctx.jobs.enqueue() delaySec');
+
+      let dedupeKey;
+      if (o.dedupeKey !== undefined && o.dedupeKey !== null) {
+        need(typeof o.dedupeKey === 'string' && o.dedupeKey.length > 0,
+             'ctx.jobs.enqueue() dedupeKey must be a non-empty string');
+        need(o.dedupeKey.length <= kMaxDedupeKey,
+             'ctx.jobs.enqueue() dedupeKey is limited to ' + kMaxDedupeKey + ' characters');
+        dedupeKey = o.dedupeKey;
+      }
+
+      // `undefined` would vanish on the way across and arrive as a missing
+      // field; null says "no payload" and survives the round trip.
+      return __hostJobs('enqueue', {
+        function_id: functionId,
+        payload: payload === undefined ? null : payload,
+        runAt: runAt,
+        delaySec: delaySec,
+        dedupeKey: dedupeKey
+      });
+    },
+
+    cancel: function (id) {
+      need(typeof id === 'string' && id.length > 0, 'ctx.jobs.cancel() takes a job id');
+      return __hostJobs('cancel', { id: id });
+    }
+  };
+
+  // --- ctx.crypto ------------------------------------------------------------
+
+  ctx.crypto = {
+    // Returns lowercase hex by default, because that is the form a webhook
+    // provider puts in its signature header (so verifying is a string
+    // comparison with nothing to decode); 'base64' is there for the providers
+    // that chose the other encoding.
+    hmacSha256: function (key, data, encoding) {
+      const enc = encoding === undefined || encoding === null ? 'hex' : encoding;
+      need(enc === 'hex' || enc === 'base64',
+           "ctx.crypto.hmacSha256() encoding must be 'hex' or 'base64'");
+      return __hostCrypto('hmacSha256', {
+        key: bytesArg(key, 'ctx.crypto.hmacSha256() key'),
+        data: bytesArg(data, 'ctx.crypto.hmacSha256() data'),
+        encoding: enc
+      });
+    },
+
+    // Native, and deliberately not implementable here: any loop written in this
+    // file is at the mercy of the engine's string representation and its early
+    // exits, which is exactly the leak this call exists to avoid.
+    timingSafeEqual: function (a, b) {
+      need(typeof a === 'string', 'ctx.crypto.timingSafeEqual() takes two strings');
+      need(typeof b === 'string', 'ctx.crypto.timingSafeEqual() takes two strings');
+      return __hostCrypto('timingSafeEqual', { a: a, b: b });
+    },
+
+    randomUUID: function () {
+      return __hostCrypto('randomUUID', {});
+    }
+  };
+
+  // --- ctx.time --------------------------------------------------------------
+
+  function zoneArg(zone, what) {
+    need(typeof zone === 'string' && zone.length > 0,
+         what + " takes an IANA zone name, e.g. 'Europe/Budapest'");
+    return zone;
+  }
+
+  function epochArg(epochMs, what) {
+    const ms = epochMs instanceof Date ? epochMs.getTime() : epochMs;
+    need(typeof ms === 'number' && Number.isFinite(ms),
+         what + ' takes epoch milliseconds or a Date');
+    return Math.floor(ms);
+  }
+
+  ctx.time = {
+    // Wall-clock fields in a zone. This is the primitive everything else is
+    // built on, and the reason it exists at all: this engine ships no Intl and
+    // no ICU, so a script has no other way to learn that 08:00 in Budapest is
+    // 06:00 UTC in winter and 07:00 in summer.
+    parts: function (epochMs, zone) {
+      return __hostTime('parts', { epochMs: epochArg(epochMs, 'ctx.time.parts()'),
+                                   zone: zoneArg(zone, 'ctx.time.parts()') });
+    },
+
+    // The inverse: the instant a wall-clock time in a zone refers to. Returns
+    // `existed` and `ambiguous` rather than hiding the two days a year when a
+    // local time does not exist or happens twice, because a job scheduled for
+    // 02:30 has to land once on both of them.
+    fromParts: function (parts, zone) {
+      need(isPlainObject(parts), 'ctx.time.fromParts() takes a parts object');
+      const z = zoneArg(zone, 'ctx.time.fromParts()');
+      const field = function (name, min, max, dflt) {
+        const v = parts[name];
+        if (v === undefined || v === null) {
+          need(dflt !== undefined, 'ctx.time.fromParts() requires ' + name);
+          return dflt;
+        }
+        need(Number.isInteger(v) && v >= min && v <= max,
+             'ctx.time.fromParts() ' + name + ' must be an integer between ' + min + ' and ' + max);
+        return v;
+      };
+      return __hostTime('fromParts', {
+        zone: z,
+        year: field('year', 1, 9999),
+        month: field('month', 1, 12),
+        day: field('day', 1, 31),
+        hour: field('hour', 0, 23, 0),
+        minute: field('minute', 0, 59, 0),
+        second: field('second', 0, 59, 0)
+      });
+    },
+
+    // So a script can validate a zone it was configured with instead of
+    // discovering it at the moment it has to render a date.
+    zoneKnown: function (zone) {
+      return __hostTime('zoneKnown', { zone: zoneArg(zone, 'ctx.time.zoneKnown()') });
+    },
+
+    // Just enough formatting to write a date line, NOT a locale library. The
+    // pattern is a token string (YYYY, MMMM, dddd, HH, mm, ...) and `locale`
+    // selects the month and weekday names; see the native side for the token
+    // table and the locales it knows.
+    format: function (epochMs, zone, pattern, locale) {
+      need(typeof pattern === 'string' && pattern.length > 0,
+           'ctx.time.format() takes a pattern string');
+      const loc = locale === undefined || locale === null ? 'en' : locale;
+      need(typeof loc === 'string' && loc.length > 0,
+           'ctx.time.format() locale must be a language tag');
+      return __hostTime('format', { epochMs: epochArg(epochMs, 'ctx.time.format()'),
+                                    zone: zoneArg(zone, 'ctx.time.format()'),
+                                    pattern: pattern, locale: loc });
+    }
+  };
+
+  // --- ctx.log ---------------------------------------------------------------
+
   ctx.log = function () {
     const parts = [];
     for (let i = 0; i < arguments.length; i++) {

+ 473 - 0
runner/src/job_worker.cpp

@@ -0,0 +1,473 @@
+#include "job_worker.hpp"
+
+#include "functions/wall_budget.hpp"
+
+#include <spdlog/spdlog.h>
+
+#include <unistd.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <random>
+#include <utility>
+
+namespace svapi::runner {
+namespace {
+
+uint64_t nowSec() {
+    return static_cast<uint64_t>(
+        std::chrono::duration_cast<std::chrono::seconds>(
+            std::chrono::system_clock::now().time_since_epoch())
+            .count());
+}
+
+std::string toHex(uint64_t v, int digits) {
+    static const char* kHex = "0123456789abcdef";
+    std::string out(static_cast<size_t>(digits), '0');
+    for (int i = digits - 1; i >= 0; --i) {
+        out[static_cast<size_t>(i)] = kHex[v & 0xf];
+        v >>= 4;
+    }
+    return out;
+}
+
+/// The refusals RunService emits with status 500 that are the RUNNER's fault,
+/// not the function's.
+///
+/// Matching on message text is a stopgap and nothing to be proud of. The
+/// protocol gives no better discriminator: a function that throws and a host
+/// context that could not be built both come back as `ok:false, status:500`,
+/// and the two want opposite retry answers - the first will throw again, the
+/// second is usually a database that was briefly away. The fix is a flag in
+/// the /run body (`runner_fault: true` on refusal()), at which point this
+/// function and its caller's special case both disappear. Until then the
+/// strings are the ones literally produced in this repository, so they move
+/// together.
+/// Whose fault the refusal was, as the runner itself reported it.
+///
+/// This used to match the error text against the three strings this repo
+/// happens to produce, because a function that threw and a runner with no
+/// runtime are both ok:false / status 500. run_service now states it outright,
+/// so the discriminator cannot drift away from the messages.
+bool isRunnerFault(const nlohmann::json& body) {
+    return body.is_object() && body.value("runner_fault", false);
+}
+
+int bodyStatus(const nlohmann::json& body, int fallback) {
+    if (body.is_object() && body.contains("status") && body.at("status").is_number_integer())
+        return body.at("status").get<int>();
+    return fallback;
+}
+
+std::string bodyError(const nlohmann::json& body) {
+    if (body.is_object() && body.contains("error") && body.at("error").is_string())
+        return body.at("error").get<std::string>();
+    return {};
+}
+
+bool bodyFlag(const nlohmann::json& body, const char* key) {
+    return body.is_object() && body.contains(key) && body.at(key).is_boolean() &&
+           body.at(key).get<bool>();
+}
+
+/// Turn a retryable failure into a retry, or into a final failure once the
+/// attempt budget is spent. Centralised so no classification path can forget
+/// the ceiling - a job that retries forever starves everything behind it.
+void applyRetry(JobDecision& decision, uint32_t attempts, uint32_t limit,
+                const JobWorkerOptions& options) {
+    if (attempts >= limit) {
+        decision.retryAfterSec = 0;
+        decision.error += " (giving up after " + std::to_string(attempts) + " attempt" +
+                          (attempts == 1 ? "" : "s") + ")";
+        return;
+    }
+    decision.retryAfterSec = retryDelaySec(attempts, options.retryBaseSec, options.retryCapSec);
+}
+
+} // namespace
+
+std::string composeRunnerId(const std::string& host, int pid, const std::string& nonce) {
+    const std::string safeHost = host.empty() ? "unknown" : host;
+    return safeHost + "/" + std::to_string(pid) + "/" + nonce;
+}
+
+std::string makeRunnerId() {
+    char host[256] = {0};
+    if (::gethostname(host, sizeof(host) - 1) != 0) host[0] = '\0';
+    std::random_device rd;
+    const uint64_t nonce = (static_cast<uint64_t>(rd()) << 32) ^ static_cast<uint64_t>(rd());
+    return composeRunnerId(host, static_cast<int>(::getpid()), toHex(nonce, 8));
+}
+
+size_t resolveWorkerCount(size_t configured, size_t poolSize) {
+    const size_t pool = poolSize == 0 ? 1 : poolSize;
+    if (configured == 0) return pool > 1 ? pool - 1 : 1;
+    return std::min(configured, pool);
+}
+
+uint32_t idleBackoffMs(uint32_t consecutiveEmptyPolls, uint32_t floorMs, uint32_t ceilMs) {
+    const uint32_t floorV = floorMs == 0 ? 1 : floorMs;
+    const uint32_t ceilV = std::max(ceilMs, floorV);
+    uint64_t delay = floorV;
+    for (uint32_t i = 0; i < consecutiveEmptyPolls && delay < ceilV; ++i) delay *= 2;
+    return static_cast<uint32_t>(std::min<uint64_t>(delay, ceilV));
+}
+
+uint32_t applyJitter(uint32_t delayMs, uint32_t percent, double unit) {
+    if (percent == 0 || delayMs == 0) return delayMs;
+    const double clamped = unit < 0.0 ? 0.0 : (unit >= 1.0 ? 0.999999 : unit);
+    const double span = static_cast<double>(delayMs) * static_cast<double>(percent) / 100.0;
+    // Centred on the nominal delay: half the draws shorten it, half lengthen
+    // it, so jitter spreads the herd without changing the average rate.
+    const double jittered = static_cast<double>(delayMs) - span + 2.0 * span * clamped;
+    return static_cast<uint32_t>(jittered < 1.0 ? 1.0 : jittered);
+}
+
+uint32_t retryDelaySec(uint32_t attempts, uint32_t baseSec, uint32_t capSec) {
+    const uint32_t base = baseSec == 0 ? 1 : baseSec;
+    const uint32_t cap = std::max(capSec, base);
+    uint64_t delay = base;
+    // attempts counts the attempt that just failed, so the first retry waits
+    // exactly `base`.
+    for (uint32_t i = 1; i < attempts && delay < cap; ++i) delay *= 3;
+    return static_cast<uint32_t>(std::min<uint64_t>(delay, cap));
+}
+
+std::string logTrigger(const std::string& jobTrigger) {
+    if (jobTrigger == "cron" || jobTrigger == "db") return jobTrigger;
+    return "job";
+}
+
+nlohmann::json buildRunRequest(const JobView& job) {
+    nlohmann::json trigger =
+        job.payload.is_object() ? job.payload : nlohmann::json::object();
+    // The scheduler owns the payload's shape; the only thing added here is the
+    // kind of trigger, and only when the payload does not already say. A
+    // function otherwise cannot tell a cron tick from a database event, and
+    // overwriting a field the scheduler set would be worse than not helping.
+    if (!trigger.contains("type")) trigger["type"] = logTrigger(job.trigger);
+    return nlohmann::json{{"project", job.project},
+                          {"function_id", job.functionId},
+                          {"trigger", std::move(trigger)}};
+}
+
+JobDecision classifyOutcome(const ProtocolResponse& response, const JobView& job,
+                            const JobWorkerOptions& options) {
+    JobDecision d;
+    const nlohmann::json& body = response.body;
+
+    // A payload the runner could not understand is a request WE built: the row
+    // is missing something, or this worker has a bug. Either way the next
+    // attempt builds the identical request.
+    if (response.httpStatus == 400) {
+        d.failure = JobFailure::Malformed;
+        d.status = 400;
+        d.error = bodyError(body).empty() ? "the runner rejected the run request"
+                                          : bodyError(body);
+        return d;
+    }
+    // The transport-level 503 (only /validate emits it today, but /run is
+    // allowed to): nothing ran.
+    if (response.httpStatus != 200) {
+        d.failure = JobFailure::RunnerFault;
+        d.status = response.httpStatus;
+        d.error = bodyError(body).empty()
+                      ? "the runner answered " + std::to_string(response.httpStatus)
+                      : bodyError(body);
+        applyRetry(d, job.attempts, options.maxAttempts, options);
+        return d;
+    }
+
+    const bool ok = body.is_object() && body.contains("ok") && body.at("ok").is_boolean() &&
+                    body.at("ok").get<bool>();
+    d.status = bodyStatus(body, ok ? 200 : 500);
+    if (ok) {
+        // The function ran and returned a valid shape. Its chosen status is
+        // recorded but means nothing here: no HTTP client exists for a cron
+        // run, so a function that deliberately returns 500 has still done its
+        // job and must not be re-run.
+        d.failure = JobFailure::None;
+        d.ok = true;
+        return d;
+    }
+
+    d.error = bodyError(body);
+    if (d.error.empty()) d.error = "the function failed without a message";
+
+    if (bodyFlag(body, "timed_out")) {
+        if (options.retryTimeouts) {
+            d.failure = JobFailure::RunnerFault;
+            applyRetry(d, job.attempts, options.maxAttempts, options);
+        } else {
+            d.failure = JobFailure::FunctionFault;
+        }
+        return d;
+    }
+    if (bodyFlag(body, "out_of_memory")) {
+        // Deterministic by construction: the ceiling is fixed per runtime, so
+        // the next attempt breaches it at the same point.
+        d.failure = JobFailure::FunctionFault;
+        return d;
+    }
+
+    switch (d.status) {
+        case 404:
+            // "Not found" OR "the registry read failed" - see the header note.
+            d.failure = JobFailure::TransientLookup;
+            applyRetry(d, job.attempts,
+                       std::min(options.lookupRetryAttempts, options.maxAttempts), options);
+            return d;
+        case 503:
+            d.failure = JobFailure::RunnerFault;
+            applyRetry(d, job.attempts, options.maxAttempts, options);
+            return d;
+        case 500:
+            if (isRunnerFault(response.body)) {
+                d.failure = JobFailure::RunnerFault;
+                applyRetry(d, job.attempts, options.maxAttempts, options);
+                return d;
+            }
+            // A throw, or a return value that is not a response. Both are the
+            // author's to fix.
+            d.failure = JobFailure::FunctionFault;
+            return d;
+        default:
+            // 409 disabled, 422 invalid / no source / does not compile, and
+            // anything else the protocol grows: all stored registry state or
+            // stored source, neither of which a retry changes.
+            d.failure = JobFailure::FunctionFault;
+            return d;
+    }
+}
+
+JobDecision classifyException(const std::string& what, const JobView& job,
+                              const JobWorkerOptions& options) {
+    JobDecision d;
+    d.failure = JobFailure::RunnerFault;
+    d.status = 500;
+    d.error = what.empty() ? "the runner threw while running the job" : what;
+    applyRetry(d, job.attempts, options.maxAttempts, options);
+    return d;
+}
+
+JobRunRecord buildRunRecord(const JobView& job, const std::string& runId, uint64_t startedAt,
+                            const nlohmann::json& runBody, const JobDecision& decision) {
+    JobRunRecord entry;
+    entry.runId = runId;
+    entry.functionId = job.functionId;
+    entry.trigger = logTrigger(job.trigger);
+    entry.ok = decision.ok;
+    entry.status = decision.status;
+    entry.error = decision.error;
+    entry.startedAt = startedAt;
+    if (runBody.is_object()) {
+        if (runBody.contains("duration_ms") && runBody.at("duration_ms").is_number())
+            entry.durationMs = runBody.at("duration_ms").get<int64_t>();
+        if (runBody.contains("console") && runBody.at("console").is_array()) {
+            const nlohmann::json& console = runBody.at("console");
+            // Bound to a named reference first: a range-for over a temporary
+            // subscript of a parsed document dangles.
+            for (const auto& line : console)
+                if (line.is_string()) entry.console.push_back(line.get<std::string>());
+        }
+        if (runBody.contains("headers") && runBody.at("headers").is_object() &&
+            !runBody.at("headers").empty())
+            entry.headers = runBody.at("headers");
+    }
+    return entry;
+}
+
+JobWorker::JobWorker(RunService& service, JobQueuePort& queue, RunLogPort& log,
+                     JobWorkerOptions options)
+    : service_(service), queue_(queue), log_(log), options_(std::move(options)) {
+    runnerId_ = options_.runnerId.empty() ? makeRunnerId() : options_.runnerId;
+    std::random_device rd;
+    rng_state_ = (static_cast<uint64_t>(rd()) << 32) ^ static_cast<uint64_t>(rd()) ^ 0x9e3779b97f4a7c15ull;
+}
+
+JobWorker::~JobWorker() { stop(); }
+
+double JobWorker::nextUnit() {
+    std::lock_guard<std::mutex> lock(rng_mutex_);
+    // xorshift64*: enough for jitter and run ids, and self-contained - the
+    // repository's randomToken() lives in a translation unit that links the
+    // session store, and neither a backoff spread nor a run id needs to be
+    // unpredictable, only unique.
+    rng_state_ ^= rng_state_ >> 12;
+    rng_state_ ^= rng_state_ << 25;
+    rng_state_ ^= rng_state_ >> 27;
+    const uint64_t v = rng_state_ * 0x2545f4914f6cdd1dull;
+    return static_cast<double>(v >> 11) / static_cast<double>(1ull << 53);
+}
+
+void JobWorker::start() {
+    if (running_.exchange(true)) return;
+    const size_t count = resolveWorkerCount(options_.workers, options_.poolSize);
+    threads_.reserve(count);
+    for (size_t i = 0; i < count; ++i) threads_.emplace_back([this] { loop(); });
+    if (options_.reclaimIntervalSec > 0)
+        maintenance_ = std::thread([this] { maintenanceLoop(); });
+    spdlog::info("job worker {} started with {} thread(s) (pool {})", runnerId_, count,
+                 options_.poolSize);
+}
+
+void JobWorker::stop() {
+    if (!running_.exchange(false)) return;
+    {
+        // Taken even though running_ is atomic: without it a thread that has
+        // evaluated the predicate but not yet waited would sleep out its full
+        // backoff after stop() had already notified.
+        std::lock_guard<std::mutex> lock(wait_mutex_);
+    }
+    wake_.notify_all();
+    for (std::thread& t : threads_)
+        if (t.joinable()) t.join();
+    threads_.clear();
+    if (maintenance_.joinable()) maintenance_.join();
+    spdlog::info("job worker {} stopped", runnerId_);
+}
+
+void JobWorker::sleepFor(uint32_t ms) {
+    std::unique_lock<std::mutex> lock(wait_mutex_);
+    wake_.wait_for(lock, std::chrono::milliseconds(ms), [this] { return !running_.load(); });
+}
+
+JobWorker::Stats JobWorker::stats() const {
+    std::lock_guard<std::mutex> lock(stats_mutex_);
+    return stats_;
+}
+
+bool JobWorker::runOnce() {
+    std::optional<JobView> job;
+    try {
+        job = queue_.claimNext(runnerId_);
+    } catch (const std::exception& e) {
+        // A failed claim is not a failed job: nothing was taken, so there is
+        // nothing to complete. Backing off is the whole response.
+        spdlog::warn("job claim failed: {}", e.what());
+        return false;
+    }
+    if (!job) return false;
+
+    {
+        std::lock_guard<std::mutex> lock(stats_mutex_);
+        ++stats_.claimed;
+    }
+
+    const uint64_t startedAt = nowSec();
+    const std::string runId = toHex(static_cast<uint64_t>(nextUnit() * 9007199254740992.0), 14) +
+                              toHex(static_cast<uint64_t>(nextUnit() * 9007199254740992.0), 14);
+
+    nlohmann::json runBody = nlohmann::json::object();
+    JobDecision decision;
+    if (job->project.empty() || job->functionId.empty()) {
+        // A row that cannot name what to run. Failed outright, and loudly: a
+        // retry would re-read the same unusable row.
+        decision.failure = JobFailure::Malformed;
+        decision.status = 400;
+        decision.error = "the job row names no project or function id";
+        spdlog::error("job {} is unusable: {}", job->jobId, decision.error);
+    } else {
+        try {
+            // RunKind::Job, explicitly. A queued run has nobody holding a
+            // socket open, so it gets the job ceiling (minutes) rather than the
+            // HTTP one (seconds). The kind is a parameter and never inferred
+            // from the descriptor, so a job-type function invoked by hand still
+            // behaves as the HTTP run it actually is.
+            const ProtocolResponse response =
+                service_.run(buildRunRequest(*job), svapi::functions::RunKind::Job);
+            runBody = response.body;
+            decision = classifyOutcome(response, *job, options_);
+        } catch (const std::exception& e) {
+            decision = classifyException(e.what(), *job, options_);
+        } catch (...) {
+            decision = classifyException("unknown error", *job, options_);
+        }
+    }
+
+    // The log is written BEFORE the queue is told, on purpose: if complete()
+    // fails, the stale sweeper will hand this job to somebody else, and the
+    // attempt that did happen should still be on record rather than vanish.
+    if (!job->project.empty() && !job->functionId.empty()) {
+        try {
+            log_.record(job->project, buildRunRecord(*job, runId, startedAt, runBody, decision));
+        } catch (const std::exception& e) {
+            spdlog::warn("could not record run {} of {}/{}: {}", runId, job->project,
+                         job->functionId, e.what());
+        }
+    }
+
+    bool completed = false;
+    try {
+        completed = queue_.complete(*job, decision.ok, decision.error, decision.retryAfterSec);
+    } catch (const std::exception& e) {
+        spdlog::warn("could not complete job {}: {}", job->jobId, e.what());
+    }
+
+    {
+        std::lock_guard<std::mutex> lock(stats_mutex_);
+        if (decision.ok) ++stats_.succeeded;
+        else if (decision.retryAfterSec > 0) ++stats_.retried;
+        else ++stats_.failed;
+        if (!completed) ++stats_.completeFailures;
+    }
+
+    if (!decision.ok) {
+        spdlog::info("job {} ({}/{}, {}) failed: {}{}", job->jobId, job->project,
+                     job->functionId, logTrigger(job->trigger), decision.error,
+                     decision.retryAfterSec > 0
+                         ? " - retrying in " + std::to_string(decision.retryAfterSec) + "s"
+                         : "");
+    } else {
+        spdlog::debug("job {} ({}/{}) ran, run {}", job->jobId, job->project, job->functionId,
+                      runId);
+    }
+    return true;
+}
+
+void JobWorker::loop() {
+    uint32_t emptyPolls = 0;
+    while (running_.load()) {
+        bool claimed = false;
+        try {
+            claimed = runOnce();
+        } catch (const std::exception& e) {
+            // runOnce already swallows what it expects; this is the net that
+            // keeps one surprise from silently ending a worker thread and
+            // leaving the process half alive.
+            spdlog::error("job worker iteration threw: {}", e.what());
+        }
+        if (claimed) {
+            emptyPolls = 0;  // a busy queue must stay responsive
+            continue;
+        }
+        const uint32_t nominal = idleBackoffMs(emptyPolls, options_.idleFloorMs,
+                                               options_.idleCeilMs);
+        if (nominal < options_.idleCeilMs) ++emptyPolls;  // stop counting at the ceiling
+        sleepFor(applyJitter(nominal, options_.jitterPercent, nextUnit()));
+    }
+}
+
+void JobWorker::maintenanceLoop() {
+    while (running_.load()) {
+        // Sleep first: a runner that has just started knows nothing a sweep
+        // would use, and vectorapi may well own the sweep anyway. Jittered so
+        // N runners restarted together do not all sweep on the same second.
+        sleepFor(applyJitter(options_.reclaimIntervalSec * 1000, options_.jitterPercent,
+                             nextUnit()));
+        if (!running_.load()) return;
+        try {
+            const uint32_t n = queue_.reclaimStale(options_.staleClaimSec, options_.maxAttempts);
+            if (n > 0) {
+                std::lock_guard<std::mutex> lock(stats_mutex_);
+                stats_.reclaimed += n;
+                spdlog::info("returned {} stale job claim(s) to pending", n);
+            }
+        } catch (const std::exception& e) {
+            spdlog::warn("stale-claim sweep failed: {}", e.what());
+        }
+    }
+}
+
+} // namespace svapi::runner

+ 355 - 0
runner/src/job_worker.hpp

@@ -0,0 +1,355 @@
+#pragma once
+#include "run_service.hpp"
+
+#include <nlohmann/json.hpp>
+
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <thread>
+#include <vector>
+
+/// The runner side of the job queue: the thread(s) that claim cron and
+/// database-event jobs and run them.
+///
+/// Contract: docs/superpowers/specs/2026-10-06-function-runtime-design.md
+/// ("Runner protocol"). vectorapi owns the scheduler - there must be exactly
+/// one, or N runners each fire every cron - and enqueues into the single global
+/// `vectorapi_function_jobs` collection. A runner CLAIMS with a
+/// compare-and-set on the row's version, so two runners racing for one job
+/// cannot both win, and a claim that goes stale returns to pending, which is
+/// how a runner dying mid-job gets retried elsewhere.
+///
+/// Three deliberate shapes, the same ones run_service.hpp has and for the same
+/// reasons:
+///
+///   1. **The same RunService the HTTP path uses.** A scheduled run and an
+///      invoked run go through one engine, one bytecode cache, one policy
+///      check and one response shaping, so "it works over HTTP but not on
+///      cron" cannot happen. This file decides only WHEN to run something and
+///      WHAT to do with the outcome.
+///   2. **No database here.** FunctionJobQueue and FunctionRunLogStore both
+///      include db_gateway.hpp, which includes the database client, which does
+///      not compile everywhere this does. So the worker talks to two
+///      ports, JobQueuePort and RunLogPort, exactly as RunService talks to
+///      FunctionSource; main.cpp adapts them over the real classes. JobView is
+///      to FunctionJob what FunctionView is to FunctionRecord.
+///   3. **Every decision is a pure function.** The retry classification, the
+///      backoff schedule, the worker count and the trigger-to-log mapping are
+///      free functions below, testable without a queue, a database or a clock.
+///      Getting the retry rule wrong either loses scheduled work or spins a job
+///      forever, and neither is something to find out in production.
+namespace svapi::runner {
+
+/// One claimed job, reduced to what running it needs.
+///
+/// `raw` is the stored row as the queue serialised it, opaque to the worker: it
+/// exists so completing a job needs no state kept between claim and complete,
+/// and so a field added to FunctionJob later does not have to be threaded
+/// through this struct to survive the round trip.
+struct JobView {
+    std::string jobId;
+    std::string project;
+    std::string functionId;
+    /// "cron" or "db". Recorded on the run log so an operator can tell why a
+    /// function ran; normalised through logTrigger() before it is stored.
+    std::string trigger;
+    /// What the function receives as its `ctx` trigger: for cron the scheduled
+    /// time, for a database event the collection, document id, event and doc.
+    nlohmann::json payload = nlohmann::json::object();
+    /// Attempts INCLUDING this one, as the queue counted it when it claimed.
+    uint32_t attempts = 1;
+    nlohmann::json raw = nlohmann::json::object();
+};
+
+/// What the worker needs from FunctionJobQueue. Implemented over the real queue
+/// in main.cpp, in-memory by the tests.
+class JobQueuePort {
+public:
+    virtual ~JobQueuePort() = default;
+
+    /// Claim the oldest due job. nullopt means "nothing to do, back off" - it
+    /// is not an error, and an empty queue is the normal case.
+    ///
+    /// Implementations must not throw: a database failure here is reported as
+    /// nullopt and logged, because a worker loop that can be killed by a
+    /// transient read is a worker loop that stops doing cron.
+    virtual std::optional<JobView> claimNext(const std::string& runnerId) = 0;
+
+    /// Finish a claimed job. `retryAfterSec` > 0 returns it to pending for
+    /// another attempt; 0 fails it outright. Which one is decided by
+    /// classifyOutcome(), never here.
+    virtual bool complete(const JobView& job, bool ok, const std::string& error,
+                          uint32_t retryAfterSec) = 0;
+
+    /// Return claims older than `timeoutSec` to pending. Only called when
+    /// Options::reclaimIntervalSec is non-zero - see that field.
+    virtual uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) = 0;
+};
+
+/// One run, in the shape FunctionRunLog stores. Mirrored rather than reused for
+/// the reason in the file comment: function_run_log.hpp reaches the database
+/// client, and this header must not.
+struct JobRunRecord {
+    std::string runId;
+    std::string functionId;
+    std::string trigger;
+    bool ok = false;
+    int status = 0;
+    int64_t durationMs = 0;
+    std::string error;
+    std::vector<std::string> console;
+    nlohmann::json headers = nlohmann::json::object();
+    uint64_t startedAt = 0;
+};
+
+/// Where a finished run is recorded. A scheduled run has to be as visible as an
+/// invoked one: nobody is holding a socket open for a cron job, so the run log
+/// is the ONLY place its console output and its error text ever appear.
+class RunLogPort {
+public:
+    virtual ~RunLogPort() = default;
+    /// Must not throw. Writing the log cannot be allowed to change the
+    /// outcome of the job, the same rule the HTTP path's recordRun() follows.
+    virtual void record(const std::string& project, const JobRunRecord& entry) = 0;
+};
+
+/// Why a job did not succeed. The whole point of the enum is that these four
+/// are not interchangeable:
+enum class JobFailure {
+    /// It worked.
+    None,
+    /// The function is broken: it threw, returned something that is not a
+    /// response, blew its memory ceiling, is disabled, is stored invalid, or
+    /// does not compile. **Never retried.** It will fail identically on the
+    /// next attempt, so a retry buys nothing and costs the queue a slot, a
+    /// runtime lease and a wall-time budget every time round.
+    FunctionFault,
+    /// The runner could not run it: no free runtime, host bindings
+    /// unavailable, an exception out of the service. **Retried.** Nothing of
+    /// the function ran, so nothing was decided about it.
+    RunnerFault,
+    /// The registry said "no such function" - which today ALSO means "the
+    /// registry read failed", because FunctionView has no third answer (see
+    /// the note on classifyOutcome). Retried a bounded number of times, then
+    /// failed: enough to survive a database blink, few enough that a genuinely
+    /// deleted function leaves the queue promptly.
+    TransientLookup,
+    /// The request the worker built was rejected as malformed, or the row has
+    /// no project or function id. That is OUR bug or a corrupt row; retrying
+    /// re-runs the same bug. **Never retried**, and logged loudly.
+    Malformed,
+};
+
+/// What to do with a finished run. `retryAfterSec` is what goes to
+/// complete(); 0 means fail outright.
+struct JobDecision {
+    JobFailure failure = JobFailure::None;
+    bool ok = false;
+    /// The status to record on the run log - the status the FUNCTION produced,
+    /// not the status of the /run call.
+    int status = 0;
+    uint32_t retryAfterSec = 0;
+    std::string error;
+};
+
+/// Knobs, all of them with a defensible default, because an operator should not
+/// have to tune a queue to get one working.
+struct JobWorkerOptions {
+    /// Stable per process, unique between processes. Empty means makeRunnerId().
+    std::string runnerId;
+
+    /// 0 means resolveWorkerCount(0, poolSize) - see that function for why it
+    /// is not simply poolSize.
+    size_t workers = 0;
+    /// JsRuntimePool size, i.e. how many runs can physically proceed at once.
+    /// The worker count is clamped to it: claiming more work than there are
+    /// runtimes leaves jobs sitting claimed while a thread blocks in
+    /// acquire(), burning the stale-claim clock for no throughput.
+    size_t poolSize = 4;
+
+    /// Idle backoff. The floor is what an immediately-following job waits; the
+    /// ceiling is the worst-case latency between an enqueue and a pickup.
+    uint32_t idleFloorMs = 250;
+    uint32_t idleCeilMs = 5000;
+    /// Spread, as a percentage of the delay, so N runners polling one global
+    /// collection do not re-synchronise into a thundering herd after any
+    /// shared pause.
+    uint32_t jitterPercent = 25;
+
+    /// Hard ceiling on attempts, whatever the failure kind. A runner-side
+    /// condition that never clears (a pool permanently exhausted, a host
+    /// context that cannot be built) would otherwise keep one job circulating
+    /// forever and starve the queue behind it.
+    uint32_t maxAttempts = 5;
+    /// Attempts allowed for JobFailure::TransientLookup before it is failed.
+    uint32_t lookupRetryAttempts = 3;
+    /// Retry backoff: 5s, 15s, 45s, ... capped here.
+    uint32_t retryBaseSec = 5;
+    uint32_t retryCapSec = 300;
+
+    /// A wall-time timeout counts as a function fault by default, so it is NOT
+    /// retried: the budget is the function's, and burning it again on every
+    /// attempt is how a slow function turns into a queue outage. Deployments
+    /// whose functions legitimately wait on flaky third parties can turn this
+    /// on and accept the cost.
+    bool retryTimeouts = false;
+
+    /// Stale-claim recovery from the runner, which is normally OFF: vectorapi
+    /// is the singleton that owns queue maintenance, and N runners all sweeping
+    /// is wasted queries. Set it on a deployment where nothing else sweeps -
+    /// without a sweeper, a job held by a runner that was SIGKILLed never comes
+    /// back.
+    uint32_t reclaimIntervalSec = 0;
+    uint32_t staleClaimSec = 300;
+};
+
+/// Compose a runner id. Three parts, each earning its place: the host says
+/// WHICH box to go look at, the pid says which process on it, and the nonce
+/// distinguishes a restarted runner from the one that died - without it a
+/// recycled pid would make a dead process's stale claim look like the live
+/// process's own work.
+std::string composeRunnerId(const std::string& host, int pid, const std::string& nonce);
+
+/// composeRunnerId() over the real hostname, pid and a random nonce.
+std::string makeRunnerId();
+
+/// How many worker threads for a pool of `poolSize`.
+///
+/// Default (configured == 0) is poolSize - 1, never below 1: the HTTP /run path
+/// shares this pool and somebody is waiting on a socket for it, so the workers
+/// leave a runtime free rather than starving an interactive request behind a
+/// batch of cron jobs. A configured count is honoured but clamped to poolSize,
+/// because beyond that it only converts free runtimes into claimed-and-waiting
+/// jobs.
+size_t resolveWorkerCount(size_t configured, size_t poolSize);
+
+/// Idle backoff schedule, doubling from the floor to the ceiling.
+/// `consecutiveEmptyPolls` is 0 for the first empty poll after any claimed job,
+/// which is what makes a busy queue stay responsive.
+uint32_t idleBackoffMs(uint32_t consecutiveEmptyPolls, uint32_t floorMs, uint32_t ceilMs);
+
+/// Spread a delay by +/- `percent`, with `unit` in [0,1) from the caller's RNG.
+/// Pure so the spread can be tested without a clock or a generator.
+uint32_t applyJitter(uint32_t delayMs, uint32_t percent, double unit);
+
+/// Retry backoff: base, base*3, base*9, ... capped. Tripling rather than
+/// doubling because the first attempt already failed on something that needs
+/// time to clear (a restarting database, a drained pool), and four attempts
+/// should span minutes, not seconds.
+uint32_t retryDelaySec(uint32_t attempts, uint32_t baseSec, uint32_t capSec);
+
+/// Normalise a job's trigger for the run log: "cron" and "db" pass through,
+/// anything else becomes "job". A closed set keeps the log's trigger column
+/// filterable, and means a corrupt row cannot write arbitrary text into a
+/// field the UI renders as a label.
+std::string logTrigger(const std::string& jobTrigger);
+
+/// THE decision. Turns a /run outcome into "done" or "pending again", purely.
+///
+/// A note on the 404 case, because it is the one seam in this design that is
+/// not clean: main.cpp's RegistryFunctionSource maps a FAILED registry read to
+/// `found = false`, because FunctionView has no third answer, and /run then
+/// refuses with 404. So "the function was deleted" and "the database blinked"
+/// arrive here identically. Failing outright would silently drop scheduled
+/// work on a transient read; retrying forever would keep a deleted function's
+/// jobs circulating. Hence JobFailure::TransientLookup and a bounded number of
+/// attempts. The real fix is a `lookupFailed` flag on FunctionView and a 503
+/// refusal for it, at which point this clause becomes a plain FunctionFault.
+JobDecision classifyOutcome(const ProtocolResponse& response, const JobView& job,
+                            const JobWorkerOptions& options);
+
+/// The outcome when RunService::run() threw. Nothing about the function was
+/// decided, so this is a RunnerFault - but it is still subject to maxAttempts,
+/// since a throw that repeats is not transient.
+JobDecision classifyException(const std::string& what, const JobView& job,
+                              const JobWorkerOptions& options);
+
+/// Build the run log row for a finished job. Separate and pure because this is
+/// what makes a scheduled run look like an invoked one in the UI, and a
+/// mismatch here is invisible until an operator cannot find a run.
+JobRunRecord buildRunRecord(const JobView& job, const std::string& runId, uint64_t startedAt,
+                            const nlohmann::json& runBody, const JobDecision& decision);
+
+/// The /run request body for a job. Pure, so the trigger a cron run sees can be
+/// asserted against the one the HTTP path sends.
+nlohmann::json buildRunRequest(const JobView& job);
+
+/// The worker. Owns its threads; starting and stopping are the whole API.
+class JobWorker {
+public:
+    JobWorker(RunService& service, JobQueuePort& queue, RunLogPort& log,
+              JobWorkerOptions options);
+    /// Stops and joins. Destroying a running worker is safe but late: main.cpp
+    /// should stop() before it tears down the service, the gateway or the log.
+    ~JobWorker();
+
+    JobWorker(const JobWorker&) = delete;
+    JobWorker& operator=(const JobWorker&) = delete;
+
+    void start();
+
+    /// Stop claiming and join. Idempotent.
+    ///
+    /// A job already in flight RUNS TO COMPLETION and its outcome is recorded:
+    /// the wall-time ceiling bounds how long that takes, and finishing is
+    /// strictly better than being killed and re-run by the stale sweeper after
+    /// a timeout. An idle thread wakes from its backoff immediately rather than
+    /// sleeping out the ceiling. A harder kill (SIGKILL, a systemd stop
+    /// timeout) leaves the claim behind, and reclaimStale() is the net - which
+    /// is what makes cron delivery AT LEAST ONCE, not exactly once.
+    void stop();
+
+    const std::string& runnerId() const { return runnerId_; }
+
+    /// Counters, for the journal and for a future /health field.
+    struct Stats {
+        uint64_t claimed = 0;
+        uint64_t succeeded = 0;
+        uint64_t retried = 0;
+        uint64_t failed = 0;
+        /// Jobs whose outcome could not be written back to the queue. Worth a
+        /// metric: every one of these is a row that will come back through the
+        /// stale sweeper and run a second time.
+        uint64_t completeFailures = 0;
+        uint64_t reclaimed = 0;
+    };
+    Stats stats() const;
+
+    /// One claim-run-complete cycle. Returns true when a job was claimed (so
+    /// the caller should poll again immediately rather than back off).
+    /// Public because it is the whole behaviour of the loop, and a test should
+    /// be able to drive it one step at a time instead of racing threads.
+    bool runOnce();
+
+private:
+    void loop();
+    void maintenanceLoop();
+    /// Interruptible sleep: returns early as soon as stop() is called.
+    void sleepFor(uint32_t ms);
+    double nextUnit();
+
+    RunService& service_;
+    JobQueuePort& queue_;
+    RunLogPort& log_;
+    JobWorkerOptions options_;
+    std::string runnerId_;
+
+    std::atomic<bool> running_{false};
+    std::mutex wait_mutex_;
+    std::condition_variable wake_;
+
+    std::vector<std::thread> threads_;
+    std::thread maintenance_;
+
+    mutable std::mutex stats_mutex_;
+    Stats stats_;
+
+    std::mutex rng_mutex_;
+    uint64_t rng_state_ = 0;
+};
+
+} // namespace svapi::runner

+ 228 - 14
runner/src/main.cpp

@@ -11,12 +11,18 @@
 // database client, which is what keeps run_service testable on a host where
 // that client cannot compile at all (CLAUDE.md).
 #include "db_gateway.hpp"
+#include "errors.hpp"
 #include "function_env.hpp"
+#include "function_jobs.hpp"
+#include "job_worker.hpp"
+#include "project_secret_store.hpp"
 #include "function_record.hpp"
 #include "runner_auth.hpp"
 #include "function_registry.hpp"
+#include "project_settings.hpp"
 #include "run_service.hpp"
 #include "runner/host_context.hpp"
+#include "settings_store.hpp"
 
 #include <svapi/version.hpp>
 
@@ -36,7 +42,9 @@
 #include <cstring>
 #include <fstream>
 #include <iostream>
+#include <map>
 #include <memory>
+#include <mutex>
 #include <string>
 #include <thread>
 #include <vector>
@@ -63,10 +71,12 @@ void onSignal(int) { g_running = false; }
 /// smartbotic-vectorapi-runner`, which is cheap: vectorapi answers 503 for the
 /// moment the runner is down and nothing is stored unvalidated.
 ///
-/// The ONE value that has to stay in step with the server is `max_wall_time_ms`:
-/// RunnerPool's readTimeoutSec must exceed it, or our read times out before the
-/// runner can report its own timeout and a caller gets a misleading 503 instead
-/// of a 504.
+/// The ONE value that has to stay in step with the server is
+/// `max_wall_time_ms`, the ceiling for HTTP-triggered runs: RunnerPool's
+/// readTimeoutSec must exceed it, or our read times out before the runner can
+/// report its own timeout and a caller gets a misleading 503 instead of a 504.
+/// The JOB ceiling is deliberately not bound by that number - a job run is
+/// claimed from the queue inside this process and no socket is waiting on it.
 struct RunnerConfig {
     std::string logLevel = "info";
     /// Loopback by default: the single-host deployment, where no token is
@@ -82,11 +92,36 @@ struct RunnerConfig {
 
     size_t poolSize = 4;
     size_t memoryLimitBytes = 128u * 1024 * 1024;
+    /// 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;
-    /// Applied when a descriptor declares no timeoutMs. 0 = use the ceiling.
+    /// 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;
+    /// 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
+    /// the hot path for a number that changes by hand.
+    int projectBudgetTtlSec = 15;
     size_t maxStackBytes = 512u * 1024;
     size_t bytecodeCacheEntries = 64;
+    /// Runtimes reserved for job runs. A separate lane, so a cron job holding a
+    /// runtime for its whole 120 s ceiling cannot take the one an interactive
+    /// route is about to need. Costs memory: the per-run ceiling is per
+    /// runtime, so this adds to poolSize rather than dividing it.
+    size_t jobPoolSize = 4;
+    /// Claiming queued work is OFF by default: a runner upgrade must not start
+    /// draining a queue in a deployment whose server has no scheduler.
+    bool     jobsEnabled   = false;
+    uint32_t jobWorkers    = 0;   ///< 0 = jobPoolSize - 1, never below 1
+    uint32_t jobMaxAttempts = 5;
+    uint32_t staleClaimSec = 300;
     /// 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.
@@ -102,16 +137,31 @@ struct RunnerConfig {
             c.readTimeoutSec = h.value("read_timeout_sec", c.readTimeoutSec);
             c.authToken = h.value("auth_token", c.authToken);
         }
+        if (j.contains("jobs") && j["jobs"].is_object()) {
+            const auto& jb = j["jobs"];
+            c.jobsEnabled    = jb.value("enabled", c.jobsEnabled);
+            c.jobWorkers     = jb.value("workers", c.jobWorkers);
+            c.jobMaxAttempts = jb.value("max_attempts", c.jobMaxAttempts);
+            c.staleClaimSec  = jb.value("stale_claim_sec", c.staleClaimSec);
+        }
         if (j.contains("database") && j["database"].is_object())
             c.dbAddress = j["database"].value("address", c.dbAddress);
         if (j.contains("runtime") && j["runtime"].is_object()) {
             const auto& r = j["runtime"];
             c.poolSize = r.value("pool_size", c.poolSize);
             c.memoryLimitBytes = r.value("memory_limit_bytes", c.memoryLimitBytes);
+            // `max_wall_time_ms` keeps its old name and its old meaning - the
+            // HTTP ceiling - so an existing conffile is not silently
+            // reinterpreted. `max_http_wall_time_ms` is the clearer spelling
+            // and wins when both are present.
             c.maxWallTimeMs = r.value("max_wall_time_ms", c.maxWallTimeMs);
+            c.maxWallTimeMs = r.value("max_http_wall_time_ms", c.maxWallTimeMs);
+            c.maxJobWallTimeMs = r.value("max_job_wall_time_ms", c.maxJobWallTimeMs);
             c.defaultWallTimeMs = r.value("default_wall_time_ms", c.defaultWallTimeMs);
+            c.projectBudgetTtlSec = r.value("project_budget_ttl_sec", c.projectBudgetTtlSec);
             c.maxStackBytes = r.value("max_stack_bytes", c.maxStackBytes);
             c.bytecodeCacheEntries = r.value("bytecode_cache_entries", c.bytecodeCacheEntries);
+            c.jobPoolSize = r.value("job_pool_size", c.jobPoolSize);
         }
         return c;
     }
@@ -125,14 +175,130 @@ struct RunnerConfig {
     }
 };
 
+/// One project's admin-set wall-time maximum, cached for a few seconds.
+///
+/// Read straight through the gateway rather than through SettingsStore, for the
+/// reason HostContext gives for doing the same: the store's bootstrap() WRITES,
+/// seeding the settings document, which a runner must never do to configuration
+/// it is only reading. The precedence itself stays in the one pure
+/// maxFunctionWallTimeMsFor().
+class ProjectWallMaxCache {
+public:
+    ProjectWallMaxCache(svapi::DbGateway& db, int ttlSec)
+        : db_(db), ttl_(std::chrono::seconds(ttlSec < 1 ? 1 : ttlSec)) {}
+
+    int64_t get(const std::string& project) {
+        const auto now = std::chrono::steady_clock::now();
+        {
+            std::lock_guard<std::mutex> lock(mu_);
+            auto it = entries_.find(project);
+            if (it != entries_.end() && now < it->second.expires) return it->second.valueMs;
+        }
+
+        int64_t valueMs = 0;
+        bool read = false;
+        try {
+            const std::string coll = svapi::qualify("default", svapi::kSettingsCollection);
+            if (auto doc = db_.client().get(coll, svapi::projectSettingsDocId(project))) {
+                const svapi::ProjectSettings p = svapi::ProjectSettings::fromJson(*doc);
+                valueMs = svapi::maxFunctionWallTimeMsFor(&p);
+            }
+            read = true;
+        } catch (const std::exception& e) {
+            // A failed read must not silently remove a project's cap, so the
+            // last known value is kept and only its expiry is pushed out. With
+            // nothing known yet the run falls back to the configured ceiling,
+            // which still bounds it - the project maximum can only narrow.
+            spdlog::warn("could not read the wall-time maximum for project {} - {}", project,
+                         e.what());
+        }
+
+        std::lock_guard<std::mutex> lock(mu_);
+        auto it = entries_.find(project);
+        if (!read && it != entries_.end()) {
+            it->second.expires = now + ttl_;
+            return it->second.valueMs;
+        }
+        entries_[project] = Entry{valueMs, now + ttl_};
+        return valueMs;
+    }
+
+private:
+    struct Entry {
+        int64_t valueMs = 0;
+        std::chrono::steady_clock::time_point expires{};
+    };
+    svapi::DbGateway& db_;
+    std::chrono::steady_clock::duration ttl_;
+    std::mutex mu_;
+    std::map<std::string, Entry> entries_;
+};
+
 /// RunService's registry seam, over the real FunctionRegistry.
 ///
 /// 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.
+/// ctx.jobs, over the real queue.
+///
+/// The authorization rule lives HERE rather than in the host context, because
+/// it needs the registry and the host context deliberately does not: a function
+/// may only enqueue something a caller could otherwise reach. Without this a
+/// script could schedule a disabled or invalid function, or name an id that
+/// does not exist and get a row nothing will ever drain.
+class QueueJobPort : public svapi::runner::JobPort {
+public:
+    QueueJobPort(svapi::FunctionJobQueue& queue, svapi::FunctionRegistry& registry)
+        : queue_(queue), registry_(registry) {}
+
+    std::string enqueue(const std::string& project, const std::string& functionId,
+                        const nlohmann::json& trigger, uint64_t runAfterEpochSec, uint32_t depth,
+                        const std::string& jobId) override {
+        // Same rule /fn/{project}/* applies: absent, disabled and invalid are
+        // one answer to a caller, so a script learns nothing about which.
+        const std::optional<svapi::FunctionRecord> target = registry_.get(project, functionId);
+        if (!target || !target->enabled || !target->valid)
+            throw svapi::ApiError(svapi::ErrCode::NotFound, "not_found",
+                                  "no enabled function '" + functionId + "' in this project");
+
+        svapi::FunctionJob job;
+        job.jobId      = jobId;   // empty: the queue mints one
+        job.project    = project;
+        job.functionId = functionId;
+        job.trigger    = "job";
+        job.payload    = trigger;
+        job.depth      = depth;
+        job.runAfter   = runAfterEpochSec;
+        const std::string id = queue_.enqueue(job);
+        if (id.empty())
+            throw svapi::ApiError(svapi::ErrCode::Unavailable, "enqueue_failed",
+                                  "the job could not be queued");
+        return id;
+    }
+
+    bool cancel(const std::string& project, const std::string& jobId) override {
+        const std::optional<svapi::FunctionJob> job = queue_.get(jobId);
+        if (!job) return false;
+        // Project checked against the ROW, not taken from the caller: a job id
+        // is global, so a matching id in another tenant's queue must not be
+        // cancellable from here.
+        if (job->project != project) return false;
+        // A claimed job may be executing this instant. Deleting the row would
+        // not stop the run, and would leave the runner completing a job that no
+        // longer exists.
+        if (job->state == "claimed") return false;
+        return queue_.remove(jobId);
+    }
+
+private:
+    svapi::FunctionJobQueue& queue_;
+    svapi::FunctionRegistry& registry_;
+};
+
 class RegistryFunctionSource : public svapi::runner::FunctionSource {
 public:
-    explicit RegistryFunctionSource(svapi::FunctionRegistry& registry) : registry_(registry) {}
+    RegistryFunctionSource(svapi::FunctionRegistry& registry, ProjectWallMaxCache& budgets)
+        : registry_(registry), budgets_(budgets) {}
 
     svapi::runner::FunctionView lookup(const std::string& project,
                                        const std::string& functionId) override {
@@ -156,18 +322,21 @@ public:
         view.enabled = row->enabled;
         view.valid = row->valid;
         view.lastError = row->lastError;
+        view.projectMaxWallTimeMs = budgets_.get(project);
         return view;
     }
 
 private:
     svapi::FunctionRegistry& registry_;
+    ProjectWallMaxCache& budgets_;
 };
 
 /// RunService's ctx seam, over the real HostContext.
 class GatewayHostBindings : public svapi::runner::HostBindingsFactory {
 public:
-    GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment)
-        : db_(db), environment_(std::move(environment)) {}
+    GatewayHostBindings(svapi::DbGateway& db, std::vector<std::string> environment,
+                        std::shared_ptr<svapi::runner::JobPort> jobs)
+        : db_(db), environment_(std::move(environment)), jobs_(std::move(jobs)) {}
 
     bool create(const Request& request, svapi::runner::HostBindingsLease& out,
                 std::string& error) override {
@@ -181,7 +350,14 @@ public:
         // (systemd loads runner.env). The project is part of each variable's
         // name, because one runner serves every project and nothing else would
         // keep one tenant's key away from another's script.
-        cfg.env = svapi::runner::functionEnvFor(request.project, environment_);
+        // Read per run, not cached: a cached secret is a rotated credential
+        // that keeps working. A database failure here throws, which create()
+        // turns into "host context unavailable" - better than a run that
+        // silently proceeds without its credentials.
+        cfg.jobs = jobs_;
+        cfg.env = svapi::runner::functionEnvFor(request.project, environment_,
+                                                svapi::ProjectSecretStore(db_).valuesFor(
+                                                    request.project));
         try {
             auto host = std::make_unique<svapi::runner::HostContext>(db_, std::move(cfg));
             svapi::runner::HostContext* raw = host.get();
@@ -205,6 +381,9 @@ public:
 private:
     svapi::DbGateway& db_;
     std::vector<std::string> environment_;
+    /// Null when the queue is not available, which ctx.jobs reports as
+    /// `jobs_unavailable` rather than pretending to enqueue.
+    std::shared_ptr<svapi::runner::JobPort> jobs_;
 };
 
 /// Parse a request body, or answer 400 with the same error envelope the rest of
@@ -268,16 +447,30 @@ int main(int argc, char** argv) {
     svapi::runner::RunServiceOptions options;
     options.poolSize = cfg.poolSize;
     options.limits.memory_limit_bytes = cfg.memoryLimitBytes;
+    options.httpWallCeilingMs = cfg.maxWallTimeMs;
+    options.jobWallCeilingMs = cfg.maxJobWallTimeMs;
+    // The engine's hard ceiling is raised to the highest of the two by
+    // RunService itself; setting it from the HTTP ceiling here would cap every
+    // job run at the HTTP budget.
     options.limits.wall_time_ms = cfg.maxWallTimeMs;
     options.limits.max_stack_bytes = cfg.maxStackBytes;
     options.defaultTimeoutMs = cfg.defaultWallTimeMs;
     options.bytecodeCacheEntries = cfg.bytecodeCacheEntries;
     options.version = svapi::VERSION;
+    options.jobPoolSize = cfg.jobPoolSize;
+
+    ProjectWallMaxCache projectBudgets(db, cfg.projectBudgetTtlSec);
+    RegistryFunctionSource source(registry, projectBudgets);
+    // The queue has to exist before the bindings that enqueue into it. ensure()
+    // is idempotent and also re-opens the collection, without which find()
+    // cannot see existing rows in this process.
+    svapi::FunctionJobQueue jobQueue(db);
+    jobQueue.ensure();
+    auto jobPort = std::make_shared<QueueJobPort>(jobQueue, registry);
 
-    RegistryFunctionSource source(registry);
     // Snapshot the environment once: it does not change under a running
     // process, and re-reading it per run would be work for no gain.
-    GatewayHostBindings host(db, svapi::runner::processEnvironment());
+    GatewayHostBindings host(db, svapi::runner::processEnvironment(), jobPort);
     svapi::runner::RunService service(source, options, &host);
 
     // The environment wins over the config file: a secret belongs in
@@ -327,7 +520,18 @@ int main(int argc, char** argv) {
     server.Post("/run", [&service](const httplib::Request& req, httplib::Response& res) {
         nlohmann::json body;
         if (!readJsonBody(req, res, body)) return;
-        reply(res, service.run(body));
+        // The kind of run is the caller's statement, not a guess: only the
+        // caller knows whether a socket is waiting on this. Absent or
+        // unrecognised means HTTP, the short budget, because that is the
+        // mistake that costs a slow run rather than a pinned runtime. A
+        // forged "job" buys nothing an attacker wants either, and this port is
+        // token-authenticated and reachable only by vectorapi.
+        const std::string kindName =
+            body.is_object() && body.contains("kind") && body.at("kind").is_string()
+                ? body.at("kind").get<std::string>()
+                : std::string();
+        reply(res, service.run(body, svapi::functions::parseRunKind(
+                                         kindName, svapi::functions::RunKind::Http)));
     });
 
     server.Post("/validate", [&service](const httplib::Request& req, httplib::Response& res) {
@@ -372,8 +576,18 @@ int main(int argc, char** argv) {
             g_running = false;
         }
     });
-    spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms)", cfg.httpBind, cfg.httpPort,
-                 cfg.poolSize, cfg.maxWallTimeMs);
+    spdlog::info("runner listening on {}:{} (pool {}, wall limit {}ms http / {}ms job)",
+                 cfg.httpBind, cfg.httpPort, cfg.poolSize, cfg.maxWallTimeMs,
+                 cfg.maxJobWallTimeMs);
+    // Only matters for a job-kind run REQUESTED OVER HTTP: the socket would be
+    // cut before the runner could report its own timeout, and the caller would
+    // read a 503 instead of a 504. Queue-claimed jobs are unaffected, which is
+    // why this is a warning and not a refusal to start.
+    if (cfg.maxJobWallTimeMs >= static_cast<int64_t>(cfg.readTimeoutSec) * 1000) {
+        spdlog::warn("the job wall ceiling ({}ms) is at or above this server's read timeout"
+                     " ({}s); a job-kind run posted to /run would have its socket cut before"
+                     " it could report a timeout", cfg.maxJobWallTimeMs, cfg.readTimeoutSec);
+    }
     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");

+ 103 - 15
runner/src/run_service.cpp

@@ -2,6 +2,7 @@
 
 #include "functions/descriptor.hpp"
 
+#include <algorithm>
 #include <utility>
 
 namespace svapi::runner {
@@ -9,7 +10,13 @@ namespace {
 
 /// A refusal that never ran any user code. `ok` is false and `status` carries
 /// the shape the caller should relay, so vectorapi can forward the body as-is.
-ProtocolResponse refusal(int functionStatus, const std::string& message) {
+/// `runnerFault` says whose problem it was, and it exists because the job
+/// worker has to decide whether to RETRY. A function that threw and a runner
+/// that had no runtime are both ok:false with status 500, and without this flag
+/// the only discriminator is the error text - which the worker was indeed
+/// matching literally. A flag cannot drift the way a string can.
+ProtocolResponse refusal(int functionStatus, const std::string& message,
+                         bool runnerFault = false) {
     ProtocolResponse out;
     out.body = {{"ok", false},
                 {"status", functionStatus},
@@ -18,6 +25,7 @@ ProtocolResponse refusal(int functionStatus, const std::string& message) {
                 {"console", nlohmann::json::array()},
                 {"duration_ms", 0},
                 {"error", message},
+                {"runner_fault", runnerFault},
                 {"timed_out", false},
                 {"out_of_memory", false}};
     return out;
@@ -113,10 +121,39 @@ int failureStatus(const JsResult& result) {
     return 500;  // out_of_memory included, for the reason given in the header
 }
 
+namespace {
+
+/// The engine ceiling has to be the highest budget any run may be granted.
+/// JsRuntime::run clamps its override to JsLimits::wall_time_ms, so leaving
+/// that at the HTTP value while the job ceiling is two minutes would kill every
+/// job run at two seconds - the exact bug the two ceilings exist to fix, only
+/// harder to see. Raised here, once, rather than relied upon in config.
+JsLimits withHardWallCeiling(JsLimits limits, int64_t httpCeilingMs, int64_t jobCeilingMs) {
+    limits.wall_time_ms = std::max({limits.wall_time_ms, httpCeilingMs, jobCeilingMs});
+    if (limits.wall_time_ms <= 0) limits.wall_time_ms = functions::kFallbackWallCeilingMs;
+    return limits;
+}
+
+} // namespace
+
 RunService::RunService(FunctionSource& source, RunServiceOptions options,
                        HostBindingsFactory* host)
     : source_(source), options_(std::move(options)), host_(host),
-      pool_(options_.poolSize == 0 ? 1 : options_.poolSize, options_.limits) {}
+      pool_(options_.poolSize == 0 ? 1 : options_.poolSize,
+            withHardWallCeiling(options_.limits, options_.httpWallCeilingMs,
+                                options_.jobWallCeilingMs)) {
+    options_.limits = withHardWallCeiling(options_.limits, options_.httpWallCeilingMs,
+                                          options_.jobWallCeilingMs);
+    if (options_.jobPoolSize > 0)
+        jobPool_ = std::make_unique<JsRuntimePool>(options_.jobPoolSize, options_.limits);
+}
+
+JsRuntimePool& RunService::poolFor(functions::RunKind kind) {
+    // A job run draws from its own lane when there is one, so a slow job cannot
+    // take the runtime an interactive route is about to need.
+    if (kind == functions::RunKind::Job && jobPool_) return *jobPool_;
+    return pool_;
+}
 
 RunService::~RunService() = default;
 
@@ -157,7 +194,7 @@ void RunService::cachePut(const std::string& contentHash, JsBytecode bytecode) {
     }
 }
 
-ProtocolResponse RunService::run(const nlohmann::json& request) {
+ProtocolResponse RunService::run(const nlohmann::json& request, functions::RunKind kind) {
     if (!request.is_object()) return badRequest("request body must be a JSON object");
     std::string error;
     const std::string project = requiredString(request, "project", error);
@@ -173,6 +210,12 @@ ProtocolResponse RunService::run(const nlohmann::json& request) {
     // state, and a cached module must never keep a function alive that an
     // operator has just turned off.
     const FunctionView fn = source_.lookup(project, functionId);
+    // A registry we could not READ is 503, not 404. For a queued job that is
+    // the difference between retrying in a few seconds and silently dropping
+    // scheduled work because the database blinked.
+    if (fn.lookupFailed)
+        return refusal(503, "could not read the function registry for project '" + project + "'",
+                       /*runnerFault*/ true);
     if (!fn.found)
         return refusal(404, "function '" + functionId + "' not found in project '" + project + "'");
     if (!fn.enabled) return refusal(409, "function '" + functionId + "' is disabled");
@@ -181,17 +224,24 @@ ProtocolResponse RunService::run(const nlohmann::json& request) {
                                 (fn.lastError.empty() ? "no stored error" : fn.lastError));
     if (fn.source.empty()) return refusal(422, "function '" + functionId + "' has no source");
 
-    // A declared timeout only ever narrows; JsRuntime::run clamps it to the
-    // configured ceiling, so a descriptor cannot buy itself more wall time.
-    int64_t wallMs = options_.defaultTimeoutMs;
+    // The whole budget decision, in one pure call. A descriptor's timeoutMs is
+    // honoured up to the ceiling for THIS kind of run and up to the project's
+    // maximum; it can never raise either.
+    functions::WallBudgetRequest budgetRequest;
+    budgetRequest.kind = kind;
     if (fn.descriptor.is_object() && fn.descriptor.contains("timeoutMs") &&
         fn.descriptor.at("timeoutMs").is_number_integer())
-        wallMs = fn.descriptor.at("timeoutMs").get<int64_t>();
-    const int64_t effectiveMs =
-        (wallMs > 0 && wallMs < options_.limits.wall_time_ms) ? wallMs : options_.limits.wall_time_ms;
-
-    auto lease = pool_.acquire();
-    if (!lease.valid()) return refusal(503, "no runtime available");
+        budgetRequest.declaredMs = fn.descriptor.at("timeoutMs").get<int64_t>();
+    budgetRequest.defaultMs = options_.defaultTimeoutMs;
+    budgetRequest.projectMaxMs = fn.projectMaxWallTimeMs;
+    budgetRequest.httpCeilingMs = options_.httpWallCeilingMs;
+    budgetRequest.jobCeilingMs = options_.jobWallCeilingMs;
+    budgetRequest.hardCeilingMs = options_.limits.wall_time_ms;
+    const functions::WallBudget budget = functions::resolveWallBudget(budgetRequest);
+    const int64_t effectiveMs = budget.effectiveMs;
+
+    auto lease = poolFor(kind).acquire();
+    if (!lease.valid()) return refusal(503, "no runtime available", /*runnerFault*/ true);
 
     std::string compileError;
     auto bytecode = bytecodeFor(fn.contentHash, fn.source, functionId + ".js", *lease,
@@ -213,7 +263,9 @@ ProtocolResponse RunService::run(const nlohmann::json& request) {
         hostRequest.deadlineMs = effectiveMs;
         std::string hostError;
         if (!host_->create(hostRequest, host, hostError))
-            return refusal(500, hostError.empty() ? "host bindings unavailable" : hostError);
+            // Ours, not the function's: nothing of the script ran.
+            return refusal(500, hostError.empty() ? "host bindings unavailable" : hostError,
+                           /*runnerFault*/ true);
     }
 
     // The base ctx is the trigger and nothing else. Identity, secrets and the
@@ -225,6 +277,19 @@ ProtocolResponse RunService::run(const nlohmann::json& request) {
     JsResult result = lease->run(*bytecode, ctxArg, effectiveMs, host.bindings.get());
 
     nlohmann::json console = nlohmann::json::array();
+    // A clamp is said out loud, in the run's own output. A function that asks
+    // for two minutes and is cut off after two seconds otherwise looks to its
+    // author like a mysterious timeout, and the one thing he needs to know -
+    // which cap did it, and therefore who can raise it - is nowhere.
+    if (budget.clampedByCeiling || budget.clampedByProjectMax) {
+        console.push_back("[warn] this " + std::string(functions::runKindName(kind)) +
+                          " run asked for " + std::to_string(budgetRequest.declaredMs > 0
+                                                                  ? budgetRequest.declaredMs
+                                                                  : budgetRequest.defaultMs) +
+                          "ms and was given " + std::to_string(effectiveMs) + "ms by the " +
+                          (budget.clampedByProjectMax ? "project's maximum"
+                                                      : "runner's wall-time ceiling"));
+    }
     for (const auto& line : result.console_output) console.push_back(line);
     if (host.collectConsole) {
         // Appended rather than interleaved: console.log goes through the engine
@@ -236,7 +301,13 @@ ProtocolResponse RunService::run(const nlohmann::json& request) {
     out.body = {{"console", console},
                 {"duration_ms", result.duration_ms},
                 {"timed_out", result.timed_out},
-                {"out_of_memory", result.out_of_memory}};
+                {"out_of_memory", result.out_of_memory},
+                // Reported because a timeout is otherwise unreadable: the same
+                // function times out at 2s over HTTP and survives 30s on cron,
+                // and nothing in the response would say why.
+                {"run_kind", std::string(functions::runKindName(kind))},
+                {"wall_budget_ms", effectiveMs},
+                {"wall_ceiling_ms", budget.ceilingMs}};
 
     if (!result.ok) {
         out.body["ok"] = false;
@@ -270,6 +341,8 @@ ProtocolResponse RunService::validate(const nlohmann::json& request) {
             ? request.at("path").get<std::string>()
             : "function.js";
 
+    // The HTTP lane on purpose: a validate is a person pushing a function and
+    // waiting on the response, not queued work.
     auto lease = pool_.acquire();
     if (!lease.valid()) {
         ProtocolResponse out;
@@ -317,8 +390,23 @@ ProtocolResponse RunService::health() {
     ProtocolResponse out;
     out.body = {{"status", "ok"},
                 {"version", options_.version},
+                // The ceilings are boot-time config an operator cannot read
+                // back any other way, and one of them constrains vectorapi's
+                // own read timeout, so /health is where they belong.
+                {"wall_time_ms",
+                 {{"http", options_.httpWallCeilingMs},
+                  {"job", options_.jobWallCeilingMs},
+                  {"hard", options_.limits.wall_time_ms},
+                  {"default", options_.defaultTimeoutMs}}},
                 {"pool",
-                 {{"size", pool_.size()}, {"idle", pool_.idle()}, {"retired", pool_.retired()}}}};
+                 {{"size", pool_.size()}, {"idle", pool_.idle()}, {"retired", pool_.retired()}}},
+                {"job_pool",
+                 jobPool_ ? nlohmann::json{{"size", jobPool_->size()},
+                                           {"idle", jobPool_->idle()},
+                                           {"retired", jobPool_->retired()}}
+                          // No lane: job runs share the pool above, which is
+                          // worth being able to see from outside.
+                          : nlohmann::json{{"shared", true}}}};
     return out;
 }
 

+ 61 - 5
runner/src/run_service.hpp

@@ -1,5 +1,6 @@
 #pragma once
 #include "apikey.hpp"
+#include "functions/wall_budget.hpp"
 #include "runner/js_runtime.hpp"
 #include <nlohmann/json.hpp>
 
@@ -37,6 +38,12 @@ namespace svapi::runner {
 /// identity, and the runner reads the code, the hash and the policy itself.
 struct FunctionView {
     bool found = false;
+    /// The registry could not be READ, as opposed to the function not existing.
+    /// The two must not collapse: for an HTTP request a wrong status is untidy,
+    /// but for a QUEUED job it decides whether scheduled work is silently
+    /// dropped on a database blink or retried. A lookup failure is a 503 the
+    /// worker comes back to; a genuine 404 is a dead job it must not retry.
+    bool lookupFailed = false;
     std::string source;
     /// Cache key for compiled bytecode. Must change whenever a source byte does,
     /// which is why it comes from the registry rather than being recomputed.
@@ -49,6 +56,14 @@ struct FunctionView {
     /// Why `valid` is false, surfaced in the refusal so the caller does not have
     /// to re-read the registry to find out.
     std::string lastError;
+    /// The project's admin-set wall-time maximum, 0 when it has none.
+    ///
+    /// It arrives through this seam rather than being read here because the
+    /// project's settings live in the database, and the whole point of
+    /// FunctionSource is that this layer never learns that. The adapter that
+    /// already reads the registry row is the one place that can read the
+    /// project's maximum at the same time.
+    int64_t projectMaxWallTimeMs = 0;
 };
 
 /// Where functions come from. Wrapped around FunctionRegistry in production;
@@ -92,12 +107,40 @@ public:
 };
 
 struct RunServiceOptions {
-    /// Ceilings, not defaults. A descriptor's `timeoutMs` narrows
-    /// `limits.wall_time_ms`; it can never raise it (JsRuntime::run clamps).
+    /// Per-run engine ceilings. `limits.wall_time_ms` is the HARD ceiling: the
+    /// constructor raises it to the highest of the two wall ceilings below,
+    /// because JsRuntime::run clamps every override to it and a hard ceiling
+    /// left at the HTTP value would silently kill every job run at two seconds.
     JsLimits limits;
     size_t poolSize = 4;
-    /// Applied when the descriptor declares no `timeoutMs`. 0 means "use the
-    /// ceiling", which is what a single-tenant deployment wants.
+    /// Runtimes reserved for JOB runs, in their own pool.
+    ///
+    /// Separate lanes, not one shared pool, because the job ceiling is minutes
+    /// and the HTTP ceiling is seconds: three job workers each holding a
+    /// runtime for 120 s would leave one runtime to serve every interactive
+    /// route, and the moment two HTTP runs overlap the second blocks in
+    /// acquire() until vectorapi's read timeout fires - a 503 from a perfectly
+    /// healthy runner. A lane makes "a cron job can never delay an interactive
+    /// route" structural rather than statistical.
+    ///
+    /// Costs memory: the per-run ceiling is per runtime, so 4 + 4 means
+    /// budgeting for 8. 0 means "no separate lane" and job runs share the HTTP
+    /// pool, which is the old behaviour and only safe with a short job ceiling.
+    size_t jobPoolSize = 4;
+
+    /// The ceiling for a run started by an HTTP request. Low on purpose: a
+    /// client is holding a socket open for it, and vectorapi's own read timeout
+    /// has to exceed this number or a timeout is reported as a 503 instead of
+    /// the truthful 504.
+    int64_t httpWallCeilingMs = 2000;
+    /// The ceiling for a run started by the job queue (cron, database events).
+    /// Nobody is waiting on a socket, and the work these do - an LLM call, an
+    /// uncached embedding search - is tens of seconds of outbound waiting, so
+    /// the HTTP ceiling would make them impossible rather than slow.
+    int64_t jobWallCeilingMs = 120000;
+
+    /// Applied when the descriptor declares no `timeoutMs`. 0 means "use
+    /// whichever cap applies", which is what a single-tenant deployment wants.
     int64_t defaultTimeoutMs = 0;
     /// Compiled modules kept in memory. In-process only: QuickJS bytecode
     /// carries no version stamp, so persisting it would need a build
@@ -130,7 +173,16 @@ public:
 
     /// POST /run. Never throws on user input: the caller is vectorapi relaying
     /// to a client, so every outcome has to be a body it can forward.
-    ProtocolResponse run(const nlohmann::json& request);
+    ///
+    /// `kind` is an argument rather than something read out of the payload or
+    /// guessed from the descriptor, because the two callers know it for certain
+    /// and nothing else does: the job worker calls this in-process and passes
+    /// Job, and the HTTP transport passes whatever the request stated (see
+    /// functions::parseRunKind), defaulting to Http. It defaults to Http here
+    /// too, so a caller that forgets gets the SHORT budget - the failure mode
+    /// is a slow run, not an HTTP request holding a pooled runtime for minutes.
+    ProtocolResponse run(const nlohmann::json& request,
+                         functions::RunKind kind = functions::RunKind::Http);
 
     /// POST /validate - compile the source and read its `on` block WITHOUT
     /// calling the default export. The engine that validates is the engine that
@@ -153,6 +205,10 @@ private:
     RunServiceOptions options_;
     HostBindingsFactory* host_;
     JsRuntimePool pool_;
+    /// Null when jobPoolSize is 0, in which case job runs use pool_.
+    std::unique_ptr<JsRuntimePool> jobPool_;
+    /// The lane this kind of run draws from.
+    JsRuntimePool& poolFor(functions::RunKind kind);
 
     std::mutex cache_mutex_;
     /// Front is most recently used; the map points into the list so a hit is a

+ 62 - 0
runner/tests/function_env_test.cpp

@@ -102,3 +102,65 @@ TEST(FunctionEnv, IgnoresMalformedEntries) {
     EXPECT_EQ(out.size(), 1u);
     EXPECT_EQ(out.at("OK"), "y");
 }
+
+// --- Stored per-project secrets, merged with the host environment ---------
+//
+// The second source: secrets a project set over the API, which exist so that
+// filling ctx.env no longer needs shell access to the runner host.
+
+TEST(FunctionEnv, StoredSecretsAppearAsCtxEnv) {
+    const nlohmann::json env = functionEnvFor("acme", {}, {{"BOT_TOKEN", "xoxb-1"}});
+    EXPECT_EQ(env.at("BOT_TOKEN"), "xoxb-1");
+    EXPECT_EQ(env.size(), 1u);
+}
+
+TEST(FunctionEnv, StoredSecretsMergeWithTheHostEnvironment) {
+    const nlohmann::json env = functionEnvFor("acme", kEnv, {{"BOT_TOKEN", "xoxb-1"}});
+    EXPECT_EQ(env.at("OPENAI_KEY"), "sk-acme") << "the host variables must survive the merge";
+    EXPECT_EQ(env.at("WEBHOOK_URL"), "https://acme.example/hook");
+    EXPECT_EQ(env.at("BOT_TOKEN"), "xoxb-1");
+    EXPECT_EQ(env.size(), 3u);
+}
+
+TEST(FunctionEnv, TheHostEnvironmentWinsOverAStoredSecret) {
+    // The precedence rule, and the reason for it: runner.env can only be
+    // written by someone on the host, so it is the override that a stolen API
+    // credential cannot shadow.
+    const nlohmann::json env = functionEnvFor("acme", kEnv, {{"OPENAI_KEY", "stored-value"}});
+    EXPECT_EQ(env.at("OPENAI_KEY"), "sk-acme");
+    EXPECT_EQ(env.size(), 2u) << "the shadowed stored secret must not appear twice";
+}
+
+TEST(FunctionEnv, StoredSecretsStillLeaveTheRunnersOwnEnvironmentInvisible) {
+    const nlohmann::json env = functionEnvFor("acme", kEnv, {{"BOT_TOKEN", "xoxb-1"}});
+    EXPECT_FALSE(env.contains("SVAPI_RUNNER_TOKEN"));
+    EXPECT_FALSE(env.contains("DATABASE_ADDRESS"));
+    EXPECT_FALSE(env.contains("PATH"));
+    EXPECT_FALSE(env.contains("HOME"));
+    for (const auto& item : env.items())
+        EXPECT_NE(item.value(), "shared-secret") << item.key() << " carries the runner's token";
+}
+
+TEST(FunctionEnv, AStoredNameThatBreaksTheRuleIsDropped) {
+    // Defence against a row written straight into the collection rather than
+    // through the validating route: __proto__ and friends never become keys of
+    // the object a script sees as ctx.env.
+    const nlohmann::json env = functionEnvFor("acme", {}, {{"__proto__", "x"},
+                                                           {"lower", "x"},
+                                                           {"HAS-DASH", "x"},
+                                                           {"9START", "x"},
+                                                           {"", "x"},
+                                                           {"GOOD_1", "keep"}});
+    EXPECT_EQ(env.size(), 1u);
+    EXPECT_EQ(env.at("GOOD_1"), "keep");
+}
+
+TEST(FunctionEnv, StoredSecretsAreUsedExactlyAsGiven) {
+    // The map is NOT filtered by a project prefix the way host variables are,
+    // because it is read from one project's own collection. That is the
+    // contract this pins: whatever is passed in is exposed, so nothing but one
+    // project's secrets may ever be assembled into it.
+    const nlohmann::json env = functionEnvFor("acme", {}, {{"KEY", "acme-only"}});
+    EXPECT_EQ(env.at("KEY"), "acme-only");
+    EXPECT_EQ(env.size(), 1u);
+}

+ 573 - 0
runner/tests/host_context_test.cpp

@@ -29,7 +29,9 @@
 #include "db_gateway.hpp"
 #include "errors.hpp"
 #include "functions/net_guard.hpp"
+#include "functions/timezone.hpp"
 #include "principal.hpp"
+#include "db_errors.hpp"
 #include "runner/host_context.hpp"
 #include "server.hpp"
 #include "runner/js_runtime.hpp"
@@ -56,6 +58,25 @@ std::string deniedMessage(const std::string& collection, const std::string& op,
 smartbotic::database::Client::QueryOptions queryOptionsFrom(const nlohmann::json& payload);
 int64_t outboundTimeoutMs(int64_t deadline_ms, int64_t elapsed_ms, int64_t requested_ms);
 
+// Bytes across a JSON boundary, write options, and the three new ctx surfaces.
+bool isValidUtf8(std::string_view s);
+std::string base64Encode(std::string_view in);
+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);
+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);
+std::string toHex(std::string_view bytes);
+std::string hmacSha256Raw(std::string_view key, std::string_view data);
+std::string dedupeJobId(const std::string& project, const std::string& functionId,
+                        const std::string& dedupeKey);
+std::string randomUuidV4();
+std::string formatInLocale(const functions::ZoneParts& p, const std::string& pattern,
+                           const std::string& locale);
+std::time_t secondsFromMs(int64_t ms);
+
 struct EgressDecision {
     bool allowed = false;
     std::string pinnedAddress;
@@ -491,3 +512,555 @@ TEST(HostDetail, AnAddressLiteralIsClassifiedWithoutAResolver) {
     EXPECT_EQ(d.pinnedAddress, "8.8.8.8");
     EXPECT_FALSE(resolved);
 }
+
+// --- bytes across a JSON boundary -------------------------------------------
+
+TEST(HostDetail, Utf8ValidationRejectsWhatTheSerialiserWouldThrowOn) {
+    // The whole point: nlohmann's dump() answers an invalid sequence with
+    // "[json.exception.type_error.316] invalid UTF-8 byte", which reaches the
+    // author naming neither the response nor the fix. Anything this accepts
+    // must survive dump(); anything it rejects must be refused with a code.
+    EXPECT_TRUE(detail::isValidUtf8(""));
+    EXPECT_TRUE(detail::isValidUtf8("plain ascii"));
+    EXPECT_TRUE(detail::isValidUtf8("Budapest, október"));       // 2-byte sequences
+    EXPECT_TRUE(detail::isValidUtf8("\xE2\x82\xAC"));            // euro sign, 3 bytes
+    EXPECT_TRUE(detail::isValidUtf8("\xF0\x9F\x8E\xB5"));        // musical note, 4 bytes
+    EXPECT_TRUE(detail::isValidUtf8(std::string("a\0b", 3)));    // an embedded NUL is valid UTF-8
+
+    EXPECT_FALSE(detail::isValidUtf8("\xFF"));                   // never a lead byte
+    EXPECT_FALSE(detail::isValidUtf8("\x80"));                   // a bare continuation byte
+    EXPECT_FALSE(detail::isValidUtf8("\xE2\x82"));               // truncated 3-byte sequence
+    EXPECT_FALSE(detail::isValidUtf8("\xC0\x80"));               // overlong NUL
+    EXPECT_FALSE(detail::isValidUtf8("\xE0\x80\x80"));           // overlong again
+    EXPECT_FALSE(detail::isValidUtf8("\xED\xA0\x80"));           // a UTF-16 surrogate
+    EXPECT_FALSE(detail::isValidUtf8("\xF4\x90\x80\x80"));       // above U+10FFFF
+    // A real MP3 frame header, which is the case that started this: it is the
+    // first thing in a voice note and it is not text.
+    EXPECT_FALSE(detail::isValidUtf8(std::string("\xFF\xFB\x90\x64", 4)));
+}
+
+TEST(HostDetail, Base64RoundTripsEveryLengthIncludingEveryPadding) {
+    // An off-by-one in the padding corrupts every attachment a function ever
+    // touches, silently, so all three residues are checked explicitly.
+    EXPECT_EQ(detail::base64Encode(""), "");
+    EXPECT_EQ(detail::base64Encode("f"), "Zg==");
+    EXPECT_EQ(detail::base64Encode("fo"), "Zm8=");
+    EXPECT_EQ(detail::base64Encode("foo"), "Zm9v");
+    EXPECT_EQ(detail::base64Encode("foob"), "Zm9vYg==");
+    EXPECT_EQ(detail::base64Encode("fooba"), "Zm9vYmE=");
+    EXPECT_EQ(detail::base64Encode("foobar"), "Zm9vYmFy");
+
+    // Every byte value, so the alphabet and the shifts are exercised whole.
+    std::string all;
+    for (int i = 0; i < 256; ++i) all.push_back(static_cast<char>(i));
+    for (size_t n = 0; n <= all.size(); ++n) {
+        const std::string chunk = all.substr(0, n);
+        auto back = detail::base64Decode(detail::base64Encode(chunk));
+        ASSERT_TRUE(back.has_value()) << "length " << n;
+        EXPECT_EQ(*back, chunk) << "length " << n;
+    }
+}
+
+TEST(HostDetail, Base64DecodingFailsRatherThanGuessing) {
+    EXPECT_FALSE(detail::base64Decode("abc").has_value());        // not a multiple of 4
+    EXPECT_FALSE(detail::base64Decode("ab-_").has_value());       // the URL-safe alphabet
+    EXPECT_FALSE(detail::base64Decode("Zm9v!!!!").has_value());   // not base64 at all
+    EXPECT_FALSE(detail::base64Decode("Zg==Zg==").has_value());   // padding mid-string
+    EXPECT_FALSE(detail::base64Decode("=Zg=").has_value());       // padding in position 0
+    EXPECT_FALSE(detail::base64Decode("Z=g=").has_value());       // a data char after padding
+}
+
+// --- write options ----------------------------------------------------------
+
+TEST(HostDetail, AnAbsentTtlIsNotZero) {
+    // 0 clears a document's expiry, absent leaves it untouched. Collapsing the
+    // two would make every plain .patch() quietly make a temporary document
+    // permanent - the bug the database itself fixed in 2.8.0.
+    EXPECT_FALSE(detail::ttlFrom(nlohmann::json::object()).has_value());
+    EXPECT_FALSE(detail::ttlFrom({{"ttl_seconds", nullptr}}).has_value());
+    EXPECT_EQ(detail::ttlFrom({{"ttl_seconds", 0}}), 0u);
+    EXPECT_EQ(detail::ttlFrom({{"ttl_seconds", 3600}}), 3600u);
+    EXPECT_THROW(detail::ttlFrom({{"ttl_seconds", -1}}), ApiError);
+    EXPECT_THROW(detail::ttlFrom({{"ttl_seconds", 1.5}}), ApiError);
+    EXPECT_THROW(detail::ttlFrom({{"ttl_seconds", "60"}}), ApiError);
+}
+
+TEST(HostDetail, IfVersionZeroIsRefusedRatherThanTreatedAsAbsent) {
+    // The first write of a document produces version 1, so 0 can never hold.
+    // Treating it as absent would turn a guarded write into an unguarded one.
+    EXPECT_FALSE(detail::ifVersionFrom(nlohmann::json::object()).has_value());
+    EXPECT_EQ(detail::ifVersionFrom({{"ifVersion", 7}}), 7u);
+    EXPECT_THROW(detail::ifVersionFrom({{"ifVersion", 0}}), ApiError);
+    EXPECT_THROW(detail::ifVersionFrom({{"ifVersion", -1}}), ApiError);
+    EXPECT_THROW(detail::ifVersionFrom({{"ifVersion", "7"}}), ApiError);
+}
+
+TEST(HostDetail, ClientMetadataIsStrippedBeforeAWriteButNothingElseIs) {
+    // Read-modify-write is the normal shape of a function, and without this the
+    // first such round trip stores a frozen `_version` as a real field that
+    // shadows the live one on every later read.
+    nlohmann::json doc = {{"_id", "x"},         {"_version", 3},
+                          {"_created_at", 1},   {"_updated_at", 2},
+                          {"_created_by", "a"}, {"_updated_by", "b"},
+                          {"name", "kept"},     {"_vector", {1.0, 2.0}},
+                          {"_mine", "kept"}};
+    const nlohmann::json out = detail::stripDbMetadata(doc);
+    EXPECT_EQ(out.size(), 3u) << out.dump();
+    EXPECT_EQ(out.at("name"), "kept");
+    // NOT stripped: _vector is a real stored field the vector path writes, and
+    // an author's own underscore-prefixed field is theirs.
+    EXPECT_TRUE(out.contains("_vector"));
+    EXPECT_TRUE(out.contains("_mine"));
+
+    // Non-objects pass through: a scalar is not a document.
+    EXPECT_TRUE(detail::stripDbMetadata(nlohmann::json(7)).is_number());
+}
+
+TEST(HostDetail, AVersionConflictIsReportedByCodeNotByMessage) {
+    using Client = smartbotic::database::Client;
+    // The database says a stale version with ErrorCode::Aborted and reports the
+    // version it actually found. This used to be detected by lower-casing the
+    // message and looking for "version conflict" in it, because the wire
+    // carried nothing else - so a reworded message would have turned a 409
+    // "re-read and re-apply" into a 503 "retry the transport", which is the
+    // opposite instruction.
+    Client::FailureDetail conflict;
+    conflict.code = Client::ErrorCode::Aborted;
+    conflict.reason = "version_conflict";
+    conflict.currentVersion = 9;
+    const svapi::ApiError e = svapi::apiErrorFor(conflict);
+    EXPECT_EQ(e.code, svapi::ErrCode::Conflict);
+    EXPECT_EQ(e.slug, "version_conflict");
+    ASSERT_TRUE(e.details.contains("current_version"));
+    EXPECT_EQ(e.details.at("current_version"), 9) << "the caller must learn what to re-read";
+
+    // A message that merely MENTIONS a conflict is not one: the code decides.
+    Client::FailureDetail impostor;
+    impostor.code = Client::ErrorCode::Unavailable;
+    impostor.message = "Version conflict";
+    EXPECT_NE(svapi::apiErrorFor(impostor).slug, "version_conflict");
+}
+
+TEST(HostDetail, AReadOnlyDatabaseIsNotAValidationError) {
+    using Client = smartbotic::database::Client;
+    // FailedPrecondition covers three unrelated refusals. Mapping the bare code
+    // to 422 told a caller that a read-only database was its own bad request,
+    // so it would fix its payload and retry forever instead of waiting.
+    Client::FailureDetail readOnly;
+    readOnly.code = Client::ErrorCode::FailedPrecondition;
+    readOnly.reason = "read_only";
+    EXPECT_EQ(svapi::apiErrorFor(readOnly).code, svapi::ErrCode::Unavailable);
+
+    Client::FailureDetail relation;
+    relation.code = Client::ErrorCode::FailedPrecondition;
+    relation.reason = "delete_restricted";
+    EXPECT_EQ(svapi::apiErrorFor(relation).code, svapi::ErrCode::Unprocessable);
+
+    // An unrecognised reason is OURS, not the caller's. Claiming "your request
+    // is invalid" when we cannot tell what refused it is worse than admitting
+    // we do not know.
+    Client::FailureDetail unknown;
+    unknown.code = Client::ErrorCode::FailedPrecondition;
+    EXPECT_EQ(svapi::apiErrorFor(unknown).code, svapi::ErrCode::Internal);
+}
+
+// --- ctx.jobs ---------------------------------------------------------------
+
+TEST(HostDetail, JobEligibilityIsRoundedUpNotDown) {
+    const int64_t now = 1800000000000LL;  // a whole number of seconds
+
+    // No scheduling at all: due immediately, which the queue already spells 0.
+    EXPECT_EQ(detail::jobRunAfterSec(nlohmann::json::object(), now), 0u);
+
+    // runAt rounds UP: the queue's granularity is seconds, and rounding down
+    // would make a job eligible BEFORE the instant the author asked for.
+    EXPECT_EQ(detail::jobRunAfterSec({{"runAt", 1800000000001LL}}, now), 1800000001u);
+    EXPECT_EQ(detail::jobRunAfterSec({{"runAt", 1800000000000LL}}, now), 1800000000u);
+    EXPECT_EQ(detail::jobRunAfterSec({{"runAt", -5}}, now), 0u);
+
+    EXPECT_EQ(detail::jobRunAfterSec({{"delaySec", 60}}, now), 1800000060u);
+    EXPECT_EQ(detail::jobRunAfterSec({{"delaySec", 0}}, now), 0u);
+}
+
+TEST(HostDetail, AnEnqueuedPayloadBecomesTheRunsCtxBody) {
+    // A job and an HTTP POST then look the same to the function being invoked,
+    // so one handler can serve both.
+    const nlohmann::json trigger =
+        detail::jobTrigger({{"order", 7}}, 3, "webhook-receiver", 1800000000000LL);
+    EXPECT_EQ(trigger.at("body").at("order"), 7);
+    EXPECT_EQ(trigger.at("trigger"), "job");
+    EXPECT_EQ(trigger.at("depth"), 3);
+    EXPECT_EQ(trigger.at("enqueued_by"), "webhook-receiver");
+    // No HTTP shape, but present and empty, so ctx.method reads as "" rather
+    // than throwing.
+    EXPECT_EQ(trigger.at("method"), "");
+}
+
+TEST(HostDetail, ADedupeKeyIsDeterministicAndScopedToTheProjectAndFunction) {
+    const std::string a = detail::dedupeJobId("acme", "ingest", "delivery-42");
+    EXPECT_EQ(a, detail::dedupeJobId("acme", "ingest", "delivery-42"))
+        << "the same key must derive the same job id, or a retried webhook enqueues twice";
+
+    // Different tenants, different functions and different keys must not
+    // collide, or one enqueue would silently overwrite another.
+    EXPECT_NE(a, detail::dedupeJobId("other", "ingest", "delivery-42"));
+    EXPECT_NE(a, detail::dedupeJobId("acme", "other", "delivery-42"));
+    EXPECT_NE(a, detail::dedupeJobId("acme", "ingest", "delivery-43"));
+    // Separator discipline: the pieces are NUL-joined, so a key containing the
+    // other fields' text cannot impersonate a different triple.
+    EXPECT_NE(detail::dedupeJobId("a", "b", "c"), detail::dedupeJobId("a", "bc", ""));
+
+    EXPECT_EQ(a.substr(0, 2), "d-") << "an operator reading the queue should be able to tell a "
+                                       "deduplicated job from a minted one";
+    EXPECT_EQ(a.size(), 34u);  // "d-" plus 128 bits of hex
+}
+
+// --- ctx.crypto -------------------------------------------------------------
+
+TEST(HostDetail, HmacSha256MatchesTheRfc4231Vectors) {
+    // Test cases 1 and 2 from RFC 4231. A webhook signature check is only as
+    // good as this digest, and a wrong one fails open for every caller who
+    // compares it to the provider's header.
+    const std::string key1(20, '\x0b');
+    EXPECT_EQ(detail::toHex(detail::hmacSha256Raw(key1, "Hi There")),
+              "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7");
+    EXPECT_EQ(detail::toHex(detail::hmacSha256Raw("Jefe", "what do ya want for nothing?")),
+              "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");
+    // An empty key is legal HMAC (zero-padded to the block size) and must not
+    // be mistaken for a failure.
+    EXPECT_EQ(detail::hmacSha256Raw("", "x").size(), 32u);
+}
+
+TEST(HostDetail, RandomUuidLooksLikeAVersion4Uuid) {
+    const std::string u = detail::randomUuidV4();
+    ASSERT_EQ(u.size(), 36u) << u;
+    EXPECT_EQ(u[8], '-');
+    EXPECT_EQ(u[13], '-');
+    EXPECT_EQ(u[18], '-');
+    EXPECT_EQ(u[23], '-');
+    EXPECT_EQ(u[14], '4') << "the version nibble";
+    EXPECT_NE(std::string("89ab").find(u[19]), std::string::npos) << "the RFC 4122 variant";
+    for (size_t i = 0; i < u.size(); ++i) {
+        if (i == 8 || i == 13 || i == 18 || i == 23) continue;
+        EXPECT_NE(std::string("0123456789abcdef").find(u[i]), std::string::npos) << u;
+    }
+    // Not a proof of randomness, but it does catch a generator that was never
+    // seeded and answers the same value forever.
+    EXPECT_NE(u, detail::randomUuidV4());
+}
+
+// --- ctx.time ---------------------------------------------------------------
+
+namespace {
+
+svapi::functions::ZoneParts budapestAutumn() {
+    // 2026-10-07T14:05:09 in Budapest, a Wednesday, during summer time.
+    svapi::functions::ZoneParts p;
+    p.year = 2026;
+    p.month = 10;
+    p.day = 7;
+    p.hour = 14;
+    p.minute = 5;
+    p.second = 9;
+    p.weekday = 3;  // Wednesday, 0 = Sunday
+    p.yearday = 280;
+    p.offsetSec = 7200;
+    p.dst = true;
+    p.abbrev = "CEST";
+    return p;
+}
+
+} // namespace
+
+TEST(HostDetail, FormattingMakesAHungarianDateLinePossible) {
+    // THE requirement: real functions failed to even register because they
+    // built an Intl.DateTimeFormat at module load, and all they wanted was
+    // this one line of output.
+    const svapi::functions::ZoneParts p = budapestAutumn();
+    EXPECT_EQ(detail::formatInLocale(p, "YYYY. MMMM D., dddd", "hu"),
+              "2026. október 7., szerda");
+    // 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.
+    EXPECT_EQ(detail::formatInLocale(p, "MMMM", "hu"), "október");
+    EXPECT_EQ(detail::formatInLocale(p, "dddd", "hu"), "szerda");
+    EXPECT_EQ(detail::formatInLocale(p, "ddd", "hu"), "Sze");
+    // The language subtag is what matches, so a full tag works too.
+    EXPECT_EQ(detail::formatInLocale(p, "MMMM", "hu-HU"), "október");
+    EXPECT_EQ(detail::formatInLocale(p, "MMMM", "HU"), "október");
+}
+
+TEST(HostDetail, TheTokenTableCoversWhatADateLineNeeds) {
+    const svapi::functions::ZoneParts p = budapestAutumn();
+    EXPECT_EQ(detail::formatInLocale(p, "YYYY-MM-DD HH:mm:ss", "en"), "2026-10-07 14:05:09");
+    EXPECT_EQ(detail::formatInLocale(p, "YY M D H m s", "en"), "26 10 7 14 5 9");
+    EXPECT_EQ(detail::formatInLocale(p, "MMMM MMM dddd ddd", "en"), "October Oct Wednesday Wed");
+    EXPECT_EQ(detail::formatInLocale(p, "hh:mm A", "en"), "02:05 PM");
+    EXPECT_EQ(detail::formatInLocale(p, "ZZ Z", "en"), "CEST +02:00");
+    // Square brackets are a literal, which is how a date line keeps its own
+    // words without them being mistaken for tokens: the D in "Datum" is not a
+    // day number.
+    EXPECT_EQ(detail::formatInLocale(p, "[Datum:] YYYY", "en"), "Datum: 2026");
+    EXPECT_THROW(detail::formatInLocale(p, "[unterminated", "en"), ApiError);
+}
+
+TEST(HostDetail, TheTwelveHourClockDoesNotWrapToZero) {
+    // The classic off-by-one: 00:05 is "12:05 AM" and 12:05 is "12:05 PM",
+    // neither of them "0:05".
+    svapi::functions::ZoneParts p = budapestAutumn();
+    p.hour = 0;
+    EXPECT_EQ(detail::formatInLocale(p, "h:mm A", "en"), "12:05 AM");
+    p.hour = 12;
+    EXPECT_EQ(detail::formatInLocale(p, "h:mm A", "en"), "12:05 PM");
+    p.hour = 23;
+    EXPECT_EQ(detail::formatInLocale(p, "h:mm A", "en"), "11:05 PM");
+}
+
+TEST(HostDetail, AnUnknownLocaleIsRefusedRatherThanServedInEnglish) {
+    // A silent English fallback makes a Hungarian report render "October" and
+    // look like a translation bug nobody can locate.
+    try {
+        detail::formatInLocale(budapestAutumn(), "MMMM", "de");
+        FAIL() << "an unknown locale must be refused";
+    } catch (const ApiError& e) {
+        EXPECT_EQ(e.slug, "unknown_locale");
+    }
+}
+
+TEST(HostDetail, NegativeEpochMillisecondsRoundTowardTheEarlierSecond) {
+    // Integer division truncates toward zero, which for a pre-1970 instant
+    // moves it FORWARD by a second and lands the civil fields on the wrong day
+    // at exactly midnight.
+    EXPECT_EQ(detail::secondsFromMs(0), 0);
+    EXPECT_EQ(detail::secondsFromMs(1500), 1);
+    EXPECT_EQ(detail::secondsFromMs(-1), -1);
+    EXPECT_EQ(detail::secondsFromMs(-1000), -1);
+    EXPECT_EQ(detail::secondsFromMs(-1500), -2);
+}
+
+// --- ctx.jobs through the engine --------------------------------------------
+
+namespace {
+
+/// A JobPort that records instead of enqueuing. The point of the seam: the
+/// rules worth testing (own project only, depth bounded, a dedupe key means one
+/// job) are all decided before the queue is reached, so they are assertable
+/// with no database behind them.
+class RecordingJobPort : public svapi::runner::JobPort {
+public:
+    struct Call {
+        std::string project;
+        std::string functionId;
+        nlohmann::json trigger;
+        uint64_t runAfter = 0;
+        uint32_t depth = 0;
+        std::string jobId;
+    };
+
+    std::vector<Call> enqueued;
+    std::vector<std::pair<std::string, std::string>> cancelled;
+    /// Set to refuse, standing in for a function the caller cannot reach.
+    bool refuse = false;
+
+    std::string enqueue(const std::string& project, const std::string& functionId,
+                        const nlohmann::json& trigger, uint64_t runAfter, uint32_t depth,
+                        const std::string& jobId) override {
+        if (refuse)
+            throw ApiError(svapi::ErrCode::NotFound, "not_found",
+                           "no such function '" + functionId + "'");
+        enqueued.push_back({project, functionId, trigger, runAfter, depth, jobId});
+        return jobId.empty() ? "minted-" + std::to_string(enqueued.size()) : jobId;
+    }
+
+    bool cancel(const std::string& project, const std::string& jobId) override {
+        cancelled.emplace_back(project, jobId);
+        return jobId != "gone";
+    }
+};
+
+} // namespace
+
+TEST(HostContext, EnqueueGoesToTheFunctionsOwnProjectAndNowhereElse) {
+    auto port = std::make_shared<RecordingJobPort>();
+    HostContextConfig cfg = httpTrigger({});
+    cfg.jobs = port;
+    auto out = runScript(std::move(cfg),
+                         "export default function (ctx) {"
+                         "  return ctx.jobs.enqueue('ingest', { order: 7 });"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(port->enqueued.size(), 1u);
+    EXPECT_EQ(port->enqueued[0].project, "acme");
+    EXPECT_EQ(port->enqueued[0].functionId, "ingest");
+    // The payload is where ctx.body reads from, so a job and an HTTP POST look
+    // the same to the function being invoked.
+    EXPECT_EQ(port->enqueued[0].trigger.at("body").at("order"), 7);
+    EXPECT_EQ(port->enqueued[0].jobId, "") << "no dedupe key means the queue mints the id";
+    EXPECT_EQ(out.result.value, "minted-1");
+}
+
+TEST(HostContext, ADedupeKeyMakesARetriedWebhookEnqueueOnce) {
+    // THE requirement. The job id is derived from the key, and the queue stores
+    // a job under its id, so two deliveries of one webhook leave one job - with
+    // no read, no lock and no window between checking and writing.
+    auto port = std::make_shared<RecordingJobPort>();
+    HostContextConfig cfg = httpTrigger({});
+    cfg.jobs = port;
+    auto out = runScript(std::move(cfg),
+                         "export default function (ctx) {"
+                         "  const a = ctx.jobs.enqueue('ingest', { n: 1 }, { dedupeKey: 'd-42' });"
+                         "  const b = ctx.jobs.enqueue('ingest', { n: 1 }, { dedupeKey: 'd-42' });"
+                         "  return { a: a, b: b, same: a === b };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("same"), true);
+    ASSERT_EQ(port->enqueued.size(), 2u);
+    EXPECT_EQ(port->enqueued[0].jobId, port->enqueued[1].jobId);
+    EXPECT_FALSE(port->enqueued[0].jobId.empty());
+}
+
+TEST(HostContext, EnqueueRefusesWithoutAJobPortRatherThanLookingLikeItWorked) {
+    // Same posture as a runner installed with no endpoints configured: a
+    // capability that was never wired fails loudly.
+    auto out = runScript(httpTrigger({}), catching("ctx.jobs.enqueue('ingest')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "jobs_unavailable");
+}
+
+TEST(HostContext, EnqueueCannotReachAFunctionThePortRefuses) {
+    // Reachability is the port's call, because it is the registry lookup
+    // `/fn/{project}/*` makes. What matters here is that the refusal arrives as
+    // a catchable error with a code rather than a silently dropped job.
+    auto port = std::make_shared<RecordingJobPort>();
+    port->refuse = true;
+    HostContextConfig cfg = httpTrigger({});
+    cfg.jobs = port;
+    auto out = runScript(std::move(cfg), catching("ctx.jobs.enqueue('not-mine')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "not_found");
+}
+
+TEST(HostContext, AJobChainIsBoundedByDepth) {
+    // A function that writes to a collection it also watches would enqueue
+    // itself forever, and so would two functions that enqueue each other. The
+    // refusal lands on the function that asked for it rather than the work
+    // vanishing downstream.
+    auto port = std::make_shared<RecordingJobPort>();
+    HostContextConfig cfg = httpTrigger({});
+    cfg.jobs = port;
+    cfg.jobDepth = 4;
+    cfg.maxJobDepth = 4;
+    auto out = runScript(std::move(cfg), catching("ctx.jobs.enqueue('ingest')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "job_depth_exceeded");
+    EXPECT_TRUE(port->enqueued.empty());
+}
+
+TEST(HostContext, DepthIncrementsAndIsReadFromEitherSide) {
+    // Whichever side threads the depth through - the explicit field or the
+    // trigger the queue stored - the chain keeps counting, so neither can
+    // accidentally reset it to zero and unbound the guard.
+    auto port = std::make_shared<RecordingJobPort>();
+    HostContextConfig cfg = httpTrigger({});
+    cfg.jobs = port;
+    cfg.trigger["depth"] = 2;
+    auto out = runScript(std::move(cfg), "export default function (ctx) {"
+                                         "  return ctx.jobs.enqueue('ingest');"
+                                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    ASSERT_EQ(port->enqueued.size(), 1u);
+    EXPECT_EQ(port->enqueued[0].depth, 3u);
+    EXPECT_EQ(port->enqueued[0].trigger.at("depth"), 3);
+}
+
+TEST(HostContext, CancelIsScopedToTheProjectAndReportsWhetherAnythingWasCancelled) {
+    auto port = std::make_shared<RecordingJobPort>();
+    HostContextConfig cfg = httpTrigger({});
+    cfg.jobs = port;
+    auto out = runScript(std::move(cfg),
+                         "export default function (ctx) {"
+                         "  return { hit: ctx.jobs.cancel('d-1'), miss: ctx.jobs.cancel('gone') };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("hit"), true);
+    EXPECT_EQ(out.result.value.at("miss"), false);
+    ASSERT_EQ(port->cancelled.size(), 2u);
+    EXPECT_EQ(port->cancelled[0].first, "acme");
+}
+
+// --- ctx.crypto and ctx.time through the engine -----------------------------
+
+TEST(HostContext, CryptoIsUsableForAWebhookSignatureCheck) {
+    // The shape this exists for, end to end: digest the body under the secret,
+    // then compare against the header in constant time.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  const sig = ctx.crypto.hmacSha256('Jefe', 'what do ya want for nothing?');"
+                         "  return { sig: sig,"
+                         "           b64: ctx.crypto.hmacSha256('Jefe', 'x', 'base64').length,"
+                         "           good: ctx.crypto.timingSafeEqual(sig, sig),"
+                         "           bad: ctx.crypto.timingSafeEqual(sig, sig.slice(0, -1) + '0'),"
+                         "           shorter: ctx.crypto.timingSafeEqual(sig, 'x'),"
+                         "           uuid: ctx.crypto.randomUUID().length };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("sig"),
+              "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");
+    EXPECT_EQ(out.result.value.at("b64"), 44);  // 32 bytes base64-encoded
+    EXPECT_EQ(out.result.value.at("good"), true);
+    EXPECT_EQ(out.result.value.at("bad"), false);
+    EXPECT_EQ(out.result.value.at("shorter"), false);
+    EXPECT_EQ(out.result.value.at("uuid"), 36);
+}
+
+TEST(HostContext, TimeAnswersCivilFieldsWithoutIntl) {
+    // Guarded on the host actually having a tz database: without tzdata there
+    // is nothing to answer with, and a test that fails for that reason would
+    // say nothing about this code.
+    if (!svapi::functions::timezoneKnown("Europe/Budapest"))
+        GTEST_SKIP() << "no tzdata for Europe/Budapest on this host";
+
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         // 2026-10-07T12:05:09Z, which is 14:05 in Budapest.
+                         "  const p = ctx.time.parts(1791374709000, 'Europe/Budapest');"
+                         "  return { line: ctx.time.format(1791374709000, 'Europe/Budapest',"
+                         "                                 'YYYY. MMMM D., dddd', 'hu'),"
+                         "           hour: p.hour, offset: p.offsetSec, zone: p.zone,"
+                         "           known: ctx.time.zoneKnown('Europe/Budapest'),"
+                         "           nonsense: ctx.time.zoneKnown('Mars/Olympus') };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("line"), "2026. október 7., szerda");
+    EXPECT_EQ(out.result.value.at("hour"), 14);
+    EXPECT_EQ(out.result.value.at("offset"), 7200);
+    EXPECT_EQ(out.result.value.at("known"), true);
+    EXPECT_EQ(out.result.value.at("nonsense"), false);
+}
+
+TEST(HostContext, AnUnknownZoneIsACatchableErrorNotASilentUtcFallback) {
+    auto out = runScript(httpTrigger({}), catching("ctx.time.parts(0, 'Mars/Olympus')"));
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("threw"), true);
+    EXPECT_EQ(out.result.value.at("code"), "unknown_timezone");
+}
+
+TEST(HostContext, FromPartsReportsASkippedLocalTimeRatherThanInventingOne) {
+    if (!svapi::functions::timezoneKnown("Europe/Budapest"))
+        GTEST_SKIP() << "no tzdata for Europe/Budapest on this host";
+    // 02:30 on the morning the clocks go forward does not exist in Budapest.
+    auto out = runScript(httpTrigger({}),
+                         "export default function (ctx) {"
+                         "  const r = ctx.time.fromParts({ year: 2026, month: 3, day: 29,"
+                         "                                 hour: 2, minute: 30 },"
+                         "                               'Europe/Budapest');"
+                         "  return { existed: r.existed, hasEpoch: typeof r.epochMs };"
+                         "}");
+    ASSERT_TRUE(out.result.ok) << out.result.error;
+    EXPECT_EQ(out.result.value.at("existed"), false);
+    EXPECT_EQ(out.result.value.at("hasEpoch"), "number");
+}

+ 522 - 0
runner/tests/host_prelude_test.cpp

@@ -0,0 +1,522 @@
+// Tests for runner/src/host_prelude.js - the argument-validation half of `ctx`.
+//
+// WHY a separate file from host_context_test.cpp: that one links runner_host,
+// which links vectorapi_core and therefore the database client, so it only
+// builds where the client does. The prelude needs none of that. It is plain
+// JavaScript, and the rule it exists to enforce is that EVERY new argument is
+// checked BEFORE any host call - which is exactly a property you can assert by
+// running the real engine with the real prelude and recording bindings that
+// count how often they were reached.
+//
+// So the prelude is loaded from its own source file and installed with
+// JavaScript recorder functions standing in for __hostDb / __hostFetch /
+// __hostLog / __hostJobs / __hostCrypto / __hostTime. No database, no OpenSSL,
+// no tz database, no quickjs.h in this translation unit.
+//
+// The two assertions that matter, and that nothing else in the suite can make:
+//
+//   "validated in the prelude BEFORE any host call" - a refusal leaves the
+//   recorder's call list EMPTY. A check that runs after the host has been
+//   reached is not a check, it is a second opinion.
+//
+//   "every refusal must reach the script as a catchable Error with a `code`" -
+//   a script branches on e.code, and matching message text is how a function
+//   breaks when a sentence is reworded.
+#include <gtest/gtest.h>
+
+#include <fstream>
+#include <sstream>
+#include <string>
+
+#include "runner/js_runtime.hpp"
+
+using svapi::runner::JsResult;
+using svapi::runner::JsRuntime;
+
+namespace {
+
+/// The editable prelude, not a generated copy: a test that reads the .js file
+/// tests the thing a maintainer edits. (The runner itself embeds it at configure
+/// time so a deployed binary has no file dependency.)
+std::string preludeSource() {
+    std::ifstream in(SVAPI_HOST_PRELUDE_PATH);
+    EXPECT_TRUE(in.good()) << "cannot read " << SVAPI_HOST_PRELUDE_PATH;
+    std::ostringstream ss;
+    ss << in.rdbuf();
+    return ss.str();
+}
+
+/// The harness: install the real prelude onto a bare object with recording
+/// bindings, run one expression, and report what the bindings saw.
+///
+/// The canned answers are shaped like the real ones only where the prelude
+/// reads them back - ctx.fetch decorates its result with json(), so that one has
+/// to be an object with a bodyEncoding.
+const char* kHarness = R"JS(
+const __installHost = %PRELUDE%;
+
+function __answer(kind) {
+  if (kind === 'fetch') {
+    return { status: 200, ok: true, headers: {}, body: '{"a":1}',
+             bodyEncoding: __base64Response ? 'base64' : 'text', bytes: 7 };
+  }
+  if (kind === 'jobs') return 'job-1';
+  if (kind === 'crypto') return 'deadbeef';
+  if (kind === 'time') return { year: 2026, month: 10, day: 7 };
+  return null;
+}
+
+let __base64Response = false;
+
+export default function () {
+  const calls = [];
+  function recorder(kind) {
+    return function () {
+      const args = [];
+      for (let i = 0; i < arguments.length; i++) args.push(arguments[i]);
+      calls.push({ kind: kind, args: args });
+      return __answer(kind);
+    };
+  }
+  const ctx = {};
+  __installHost(ctx, recorder('db'), recorder('fetch'), recorder('log'),
+                recorder('jobs'), recorder('crypto'), recorder('time'));
+
+  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 { calls: calls, value: value === undefined ? null : value, threw: threw };
+}
+)JS";
+
+nlohmann::json runPrelude(const std::string& body) {
+    static const std::string prelude = preludeSource();
+    std::string src = kHarness;
+    src.replace(src.find("%PRELUDE%"), std::string("%PRELUDE%").size(), prelude);
+    src.replace(src.find("%BODY%"), std::string("%BODY%").size(), body);
+
+    JsRuntime rt;
+    std::string error;
+    auto bc = rt.compile(src, "host_prelude_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;
+}
+
+/// A refusal: it threw, it carries `code`, and it never reached the host.
+void expectRefused(const std::string& body, const std::string& code) {
+    const nlohmann::json out = runPrelude(body);
+    ASSERT_TRUE(out.contains("threw")) << body;
+    ASSERT_FALSE(out.at("threw").is_null()) << body << " was expected to throw";
+    EXPECT_EQ(out.at("threw").at("code"), code) << body << " -> " << out.at("threw").dump();
+    EXPECT_EQ(out.at("calls").size(), 0u)
+        << body << " reached the host before refusing: " << out.at("calls").dump();
+}
+
+/// The single host call an accepted expression made.
+nlohmann::json onlyCall(const nlohmann::json& out, const std::string& kind) {
+    EXPECT_TRUE(out.at("threw").is_null()) << out.at("threw").dump();
+    EXPECT_EQ(out.at("calls").size(), 1u) << out.at("calls").dump();
+    if (out.at("calls").size() != 1) return nlohmann::json::object();
+    const nlohmann::json& call = out.at("calls").at(0);
+    EXPECT_EQ(call.at("kind"), kind);
+    return call.at("args");
+}
+
+} // namespace
+
+// --- the prelude itself -----------------------------------------------------
+
+TEST(HostPrelude, InstallsTheWholeCtxSurface) {
+    const nlohmann::json out = runPrelude(
+        "return { collections: typeof ctx.collections, fetch: typeof ctx.fetch,"
+        "         log: typeof ctx.log, enqueue: typeof ctx.jobs.enqueue,"
+        "         cancel: typeof ctx.jobs.cancel, hmac: typeof ctx.crypto.hmacSha256,"
+        "         tse: typeof ctx.crypto.timingSafeEqual,"
+        "         uuid: typeof ctx.crypto.randomUUID, parts: typeof ctx.time.parts,"
+        "         fromParts: typeof ctx.time.fromParts, format: typeof ctx.time.format,"
+        "         zoneKnown: typeof ctx.time.zoneKnown };");
+    for (auto it = out.at("value").begin(); it != out.at("value").end(); ++it)
+        EXPECT_EQ(it.value(), "function") << it.key() << " is missing from ctx";
+}
+
+TEST(HostPrelude, TheBindingsAreNotReachableFromUserCode) {
+    // The whole reason they are parameters rather than globals: a script that
+    // could call __hostDb directly would skip every check in this file.
+    const nlohmann::json out = runPrelude(
+        "return { db: typeof globalThis.__hostDb, jobs: typeof globalThis.__hostJobs,"
+        "         crypto: typeof globalThis.__hostCrypto, time: typeof globalThis.__hostTime };");
+    for (auto it = out.at("value").begin(); it != out.at("value").end(); ++it)
+        EXPECT_EQ(it.value(), "undefined") << it.key() << " leaked onto globalThis";
+}
+
+// --- ctx.fetch: binary bodies -----------------------------------------------
+
+TEST(HostPrelude, FetchDefaultsToTextAndIsOtherwiseUnchanged) {
+    // "Default behaviour must not change": no responseType means text, and no
+    // body option means no body fields on the way to the host.
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.fetch('https://x.example/');"), "fetch");
+    ASSERT_EQ(args.size(), 2u);
+    EXPECT_EQ(args.at(0), "https://x.example/");
+    EXPECT_EQ(args.at(1).at("responseType"), "text");
+    // ABSENT, not null: an option the caller did not give is left `undefined`,
+    // which JSON drops on the way to the host - which is in turn why every
+    // reader on the native side tests contains() rather than is_null().
+    EXPECT_FALSE(args.at(1).contains("body"));
+    EXPECT_FALSE(args.at(1).contains("bodyBase64"));
+    EXPECT_FALSE(args.at(1).contains("bodyBytes"));
+}
+
+TEST(HostPrelude, FetchForwardsABase64ResponseTypeAndRefusesAnyOther) {
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.fetch('https://x.example/', { responseType: 'base64' });"), "fetch");
+    EXPECT_EQ(args.at(1).at("responseType"), "base64");
+
+    expectRefused("return ctx.fetch('https://x.example/', { responseType: 'bytes' });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { responseType: 7 });", "validation");
+}
+
+TEST(HostPrelude, FetchValidatesBase64BeforeSendingIt) {
+    // A truncated or URL-safe-alphabet string is caught here, where the author
+    // can read the complaint, rather than on the far side of the boundary.
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBase64: 'abc' });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBase64: 'ab-_' });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBase64: 42 });", "validation");
+
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.fetch('https://x.example/', { method: 'POST', bodyBase64: 'aGk=' });"),
+        "fetch");
+    EXPECT_EQ(args.at(1).at("bodyBase64"), "aGk=");
+    EXPECT_FALSE(args.at(1).contains("body"));
+}
+
+TEST(HostPrelude, FetchValidatesEveryByteOfAByteArray) {
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBytes: [1, 256] });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBytes: [1, -1] });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBytes: [1, 1.5] });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBytes: 'abc' });", "validation");
+
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.fetch('https://x.example/', { bodyBytes: [0, 127, 255] });"), "fetch");
+    EXPECT_EQ(args.at(1).at("bodyBytes"), nlohmann::json({0, 127, 255}));
+}
+
+TEST(HostPrelude, AByteArrayIsCappedAndPointsAtTheShapeThatScales) {
+    // Every element costs several bytes as JSON on the way to the host, so a
+    // large payload belongs in base64. The cap says so with its own code rather
+    // than looking like a malformed byte.
+    expectRefused("const a = new Array(1024 * 1024 + 1).fill(0);"
+                  "return ctx.fetch('https://x.example/', { bodyBytes: a });",
+                  "body_too_large");
+}
+
+TEST(HostPrelude, TwoRequestBodiesAreAmbiguousNotAPreference) {
+    // Reading one and ignoring the other would send the wrong bytes with
+    // nothing anywhere to say so.
+    expectRefused("return ctx.fetch('https://x.example/', { body: 'a', bodyBase64: 'aGk=' });",
+                  "ambiguous_body");
+    expectRefused("return ctx.fetch('https://x.example/', { body: 'a', bodyBytes: [1] });",
+                  "ambiguous_body");
+    expectRefused("return ctx.fetch('https://x.example/', { bodyBase64: 'aGk=', bodyBytes: [1] });",
+                  "ambiguous_body");
+}
+
+TEST(HostPrelude, ATextBodyMustStillBeAStringAndNotSilentlyCoerced) {
+    expectRefused("return ctx.fetch('https://x.example/', { body: { a: 1 } });", "validation");
+    expectRefused("return ctx.fetch('https://x.example/', { body: 7 });", "validation");
+}
+
+TEST(HostPrelude, JsonRefusesABase64BodyInsteadOfParsingIt) {
+    // JSON.parse of base64 throws a SyntaxError about position 0, which tells
+    // the author nothing about the responseType they chose two lines earlier.
+    const nlohmann::json out = runPrelude(
+        "__base64Response = true;"
+        "const r = ctx.fetch('https://x.example/', { responseType: 'base64' });"
+        "try { r.json(); return 'parsed'; } catch (e) { return e.code; }");
+    EXPECT_EQ(out.at("value"), "not_json");
+
+    const nlohmann::json ok = runPrelude(
+        "const r = ctx.fetch('https://x.example/');"
+        "return r.json().a;");
+    EXPECT_EQ(ok.at("value"), 1);
+}
+
+// --- ctx.jobs ---------------------------------------------------------------
+
+TEST(HostPrelude, EnqueueNeedsAFunctionIdAndTakesNoProject) {
+    expectRefused("return ctx.jobs.enqueue();", "validation");
+    expectRefused("return ctx.jobs.enqueue('');", "validation");
+    expectRefused("return ctx.jobs.enqueue(7);", "validation");
+
+    // There is no project argument to pass, so a script cannot aim an enqueue
+    // at another tenant. The host supplies it.
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.jobs.enqueue('other-fn');"), "jobs");
+    EXPECT_EQ(args.at(0), "enqueue");
+    EXPECT_EQ(args.at(1).at("function_id"), "other-fn");
+    EXPECT_FALSE(args.at(1).contains("project"));
+}
+
+TEST(HostPrelude, AnAbsentPayloadArrivesAsNullNotAsAMissingField) {
+    // `undefined` vanishes on the way across; null survives and says
+    // "deliberately no payload".
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.jobs.enqueue('f');"), "jobs");
+    EXPECT_TRUE(args.at(1).at("payload").is_null());
+
+    const nlohmann::json withPayload =
+        onlyCall(runPrelude("return ctx.jobs.enqueue('f', { order: 7 });"), "jobs");
+    EXPECT_EQ(withPayload.at(1).at("payload").at("order"), 7);
+}
+
+TEST(HostPrelude, RunAtTakesADateOrEpochMillisecondsAndNothingElse) {
+    const nlohmann::json fromDate = onlyCall(
+        runPrelude("return ctx.jobs.enqueue('f', null, { runAt: new Date(1800000000000) });"), "jobs");
+    EXPECT_EQ(fromDate.at(1).at("runAt"), 1800000000000LL);
+
+    const nlohmann::json fromNumber = onlyCall(
+        runPrelude("return ctx.jobs.enqueue('f', null, { runAt: 1800000000000 });"), "jobs");
+    EXPECT_EQ(fromNumber.at(1).at("runAt"), 1800000000000LL);
+
+    expectRefused("return ctx.jobs.enqueue('f', null, { runAt: '2026-01-01' });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, { runAt: new Date('nonsense') });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, { runAt: -1 });", "validation");
+}
+
+TEST(HostPrelude, RunAtAndDelaySecCannotBothBeGiven) {
+    // Any rule for reconciling them (earliest wins? last wins?) is a guess at
+    // what the author meant.
+    expectRefused("return ctx.jobs.enqueue('f', null, { runAt: 1, delaySec: 1 });", "ambiguous_body");
+}
+
+TEST(HostPrelude, DelaySecIsANonNegativeInteger) {
+    expectRefused("return ctx.jobs.enqueue('f', null, { delaySec: -1 });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, { delaySec: 1.5 });", "validation");
+    const nlohmann::json args =
+        onlyCall(runPrelude("return ctx.jobs.enqueue('f', null, { delaySec: 60 });"), "jobs");
+    EXPECT_EQ(args.at(1).at("delaySec"), 60);
+}
+
+TEST(HostPrelude, ADedupeKeyIsANonEmptyBoundedString) {
+    expectRefused("return ctx.jobs.enqueue('f', null, { dedupeKey: '' });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, { dedupeKey: 7 });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, { dedupeKey: 'x'.repeat(513) });", "validation");
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.jobs.enqueue('f', null, { dedupeKey: 'delivery-42' });"), "jobs");
+    EXPECT_EQ(args.at(1).at("dedupeKey"), "delivery-42");
+}
+
+TEST(HostPrelude, AMisspeltEnqueueOptionIsRefusedRatherThanIgnored) {
+    // A typo'd `delaySecs` that is silently dropped is a job that fires
+    // immediately and an author who will never find out why.
+    expectRefused("return ctx.jobs.enqueue('f', null, { delaySecs: 60 });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, { dedupe: 'x' });", "validation");
+    expectRefused("return ctx.jobs.enqueue('f', null, [1, 2]);", "validation");
+}
+
+TEST(HostPrelude, CancelTakesAJobId) {
+    expectRefused("return ctx.jobs.cancel();", "validation");
+    expectRefused("return ctx.jobs.cancel('');", "validation");
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.jobs.cancel('d-abc');"), "jobs");
+    EXPECT_EQ(args.at(0), "cancel");
+    EXPECT_EQ(args.at(1).at("id"), "d-abc");
+}
+
+// --- ctx.crypto -------------------------------------------------------------
+
+TEST(HostPrelude, HmacTakesStringsOrBase64AndOneOfTwoEncodings) {
+    const nlohmann::json hex =
+        onlyCall(runPrelude("return ctx.crypto.hmacSha256('k', 'body');"), "crypto");
+    EXPECT_EQ(hex.at(0), "hmacSha256");
+    EXPECT_EQ(hex.at(1).at("key").at("text"), "k");
+    EXPECT_EQ(hex.at(1).at("data").at("text"), "body");
+    EXPECT_EQ(hex.at(1).at("encoding"), "hex") << "hex is the default because that is what a "
+                                                  "signature header carries";
+
+    const nlohmann::json b64 = onlyCall(
+        runPrelude("return ctx.crypto.hmacSha256({ base64: 'aGk=' }, 'body', 'base64');"), "crypto");
+    EXPECT_EQ(b64.at(1).at("key").at("base64"), "aGk=");
+    EXPECT_EQ(b64.at(1).at("encoding"), "base64");
+
+    expectRefused("return ctx.crypto.hmacSha256('k', 'b', 'hex2');", "validation");
+    expectRefused("return ctx.crypto.hmacSha256(null, 'b');", "validation");
+    expectRefused("return ctx.crypto.hmacSha256('k', 7);", "validation");
+    expectRefused("return ctx.crypto.hmacSha256({ base64: 'zzz' }, 'b');", "validation");
+}
+
+TEST(HostPrelude, TimingSafeEqualTakesTwoStringsAndIsNotImplementedHere) {
+    expectRefused("return ctx.crypto.timingSafeEqual('a', 7);", "validation");
+    expectRefused("return ctx.crypto.timingSafeEqual(undefined, 'a');", "validation");
+    // Reaching the host is the point: any comparison loop written in JavaScript
+    // is at the mercy of the engine's early exits, which is the leak this call
+    // exists to avoid.
+    const nlohmann::json args =
+        onlyCall(runPrelude("return ctx.crypto.timingSafeEqual('a', 'b');"), "crypto");
+    EXPECT_EQ(args.at(0), "timingSafeEqual");
+}
+
+TEST(HostPrelude, RandomUuidIsAHostCall) {
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.crypto.randomUUID();"), "crypto");
+    EXPECT_EQ(args.at(0), "randomUUID");
+}
+
+// --- ctx.time ---------------------------------------------------------------
+
+TEST(HostPrelude, TimePartsNeedsAnInstantAndAZone) {
+    expectRefused("return ctx.time.parts(Date.now());", "validation");
+    expectRefused("return ctx.time.parts('now', 'Europe/Budapest');", "validation");
+    expectRefused("return ctx.time.parts(Date.now(), '');", "validation");
+
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.time.parts(new Date(1800000000000), 'Europe/Budapest');"), "time");
+    EXPECT_EQ(args.at(0), "parts");
+    EXPECT_EQ(args.at(1).at("epochMs"), 1800000000000LL);
+    EXPECT_EQ(args.at(1).at("zone"), "Europe/Budapest");
+}
+
+TEST(HostPrelude, FromPartsRequiresTheDateAndDefaultsTheTime) {
+    expectRefused("return ctx.time.fromParts({ month: 1, day: 1 }, 'Europe/Budapest');", "validation");
+    expectRefused("return ctx.time.fromParts({ year: 2026, month: 13, day: 1 }, 'Europe/Budapest');",
+                  "validation");
+    expectRefused("return ctx.time.fromParts({ year: 2026, month: 1, day: 0 }, 'Europe/Budapest');",
+                  "validation");
+    expectRefused("return ctx.time.fromParts('2026-01-01', 'Europe/Budapest');", "validation");
+
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.time.fromParts({ year: 2026, month: 3, day: 29, hour: 2, minute: 30 },"
+                   "                          'Europe/Budapest');"),
+        "time");
+    EXPECT_EQ(args.at(1).at("year"), 2026);
+    EXPECT_EQ(args.at(1).at("hour"), 2);
+    EXPECT_EQ(args.at(1).at("second"), 0) << "an omitted time field defaults rather than refusing";
+}
+
+TEST(HostPrelude, FormatNeedsAPatternAndDefaultsTheLocale) {
+    expectRefused("return ctx.time.format(Date.now(), 'Europe/Budapest');", "validation");
+    expectRefused("return ctx.time.format(Date.now(), 'Europe/Budapest', '');", "validation");
+    expectRefused("return ctx.time.format(Date.now(), 'Europe/Budapest', 'YYYY', 7);", "validation");
+
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.time.format(0, 'Europe/Budapest', 'YYYY. MMMM D., dddd', 'hu');"),
+        "time");
+    EXPECT_EQ(args.at(1).at("pattern"), "YYYY. MMMM D., dddd");
+    EXPECT_EQ(args.at(1).at("locale"), "hu");
+
+    const nlohmann::json dflt =
+        onlyCall(runPrelude("return ctx.time.format(0, 'UTC', 'YYYY');"), "time");
+    EXPECT_EQ(dflt.at(1).at("locale"), "en");
+}
+
+TEST(HostPrelude, ZoneKnownTakesAZoneName) {
+    expectRefused("return ctx.time.zoneKnown(7);", "validation");
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.time.zoneKnown('UTC');"), "time");
+    EXPECT_EQ(args.at(0), "zoneKnown");
+}
+
+// --- write options ----------------------------------------------------------
+
+TEST(HostPrelude, TtlSecondsIsForwardedOnEveryWriteAndValidatedTheSameWay) {
+    struct Case { const char* call; const char* op; };
+    const Case cases[] = {
+        {"return ctx.collections('c').insert({ a: 1 }, { ttl_seconds: 60 });", "insert"},
+        {"return ctx.collections('c').update('x', { a: 1 }, { ttl_seconds: 60 });", "update"},
+        {"return ctx.collections('c').patch('x', { a: 1 }, { ttl_seconds: 60 });", "patch"},
+    };
+    for (const auto& c : cases) {
+        const nlohmann::json args = onlyCall(runPrelude(c.call), "db");
+        EXPECT_EQ(args.at(1), c.op);
+        EXPECT_EQ(args.at(2).at("ttl_seconds"), 60) << c.call;
+    }
+
+    expectRefused("return ctx.collections('c').insert({ a: 1 }, { ttl_seconds: -1 });", "validation");
+    expectRefused("return ctx.collections('c').patch('x', {}, { ttl_seconds: 1.5 });", "validation");
+    expectRefused("return ctx.collections('c').patch('x', {}, { ttl_seconds: '60' });", "validation");
+}
+
+TEST(HostPrelude, AnAbsentTtlStaysAbsentRatherThanBecomingZero) {
+    // 0 CLEARS a document's expiry while absent leaves it alone. Collapsing the
+    // two here would make every plain .patch() quietly make a temporary
+    // document permanent.
+    const nlohmann::json args = onlyCall(runPrelude("return ctx.collections('c').patch('x', {});"), "db");
+    EXPECT_FALSE(args.at(2).contains("ttl_seconds"));
+    EXPECT_FALSE(args.at(2).contains("ifVersion"));
+
+    const nlohmann::json zero =
+        onlyCall(runPrelude("return ctx.collections('c').patch('x', {}, { ttl_seconds: 0 });"), "db");
+    EXPECT_EQ(zero.at(2).at("ttl_seconds"), 0);
+}
+
+TEST(HostPrelude, IfVersionMustBeAStoredVersionNumber) {
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.collections('c').patch('x', { a: 1 }, { ifVersion: 3 });"), "db");
+    EXPECT_EQ(args.at(2).at("ifVersion"), 3);
+
+    // The first write of a document produces version 1, so 0 is a precondition
+    // that can never hold; accepting it would turn a guarded write into an
+    // unguarded one.
+    expectRefused("return ctx.collections('c').patch('x', {}, { ifVersion: 0 });", "validation");
+    expectRefused("return ctx.collections('c').patch('x', {}, { ifVersion: -1 });", "validation");
+    expectRefused("return ctx.collections('c').patch('x', {}, { ifVersion: '3' });", "validation");
+}
+
+TEST(HostPrelude, TtlAndIfVersionCannotBeCombined) {
+    // Optimistic locking is a whole-document replace on the far side, and that
+    // call carries no expiry argument. Dropping the TTL silently would leave a
+    // document that was meant to expire living forever.
+    expectRefused("return ctx.collections('c').patch('x', {}, { ttl_seconds: 60, ifVersion: 3 });",
+                  "unsupported_combination");
+    expectRefused("return ctx.collections('c').update('x', {}, { ttl_seconds: 60, ifVersion: 3 });",
+                  "unsupported_combination");
+}
+
+TEST(HostPrelude, AnOptionTheCallDoesNotTakeIsRefused) {
+    // .insert() has no version to check against - the document does not exist
+    // yet - so accepting ifVersion there would be a precondition that does
+    // nothing, which is worse than an error.
+    expectRefused("return ctx.collections('c').insert({ a: 1 }, { ifVersion: 3 });", "validation");
+    expectRefused("return ctx.collections('c').patch('x', {}, { ttlSeconds: 60 });", "validation");
+}
+
+TEST(HostPrelude, StoreTakesTheSameExpiryAnInsertDoes) {
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.collections('v').store({ vector: [1, 2], ttl_seconds: 300 });"), "db");
+    EXPECT_EQ(args.at(1), "store");
+    EXPECT_EQ(args.at(2).at("ttl_seconds"), 300);
+
+    expectRefused("return ctx.collections('v').store({ vector: [1], ttl_seconds: -5 });", "validation");
+}
+
+// --- what did NOT change ----------------------------------------------------
+
+TEST(HostPrelude, TheExistingBuilderStillBehavesExactlyAsBefore) {
+    const nlohmann::json args = onlyCall(
+        runPrelude("return ctx.collections('c').filter('a:eq:1').sort('-created_at').limit(5)"
+                   "          .offset(2).find();"),
+        "db");
+    EXPECT_EQ(args.at(1), "find");
+    EXPECT_EQ(args.at(2).at("filters"), nlohmann::json({"a:eq:1"}));
+    EXPECT_EQ(args.at(2).at("sort"), "created_at");
+    EXPECT_EQ(args.at(2).at("desc"), true);
+    EXPECT_EQ(args.at(2).at("limit"), 5);
+    EXPECT_EQ(args.at(2).at("offset"), 2);
+}
+
+TEST(HostPrelude, TheBuilderIsStillImmutable) {
+    const nlohmann::json out = runPrelude(
+        "const base = ctx.collections('c');"
+        "const a = base.filter('x:eq:1');"
+        "return { base: base._query().filters.length, a: a._query().filters.length };");
+    EXPECT_EQ(out.at("value").at("base"), 0);
+    EXPECT_EQ(out.at("value").at("a"), 1);
+}
+
+TEST(HostPrelude, LogStillFormatsObjectsAsJson) {
+    const nlohmann::json out = runPrelude("ctx.log('two', 2, { a: 1 }); return null;");
+    ASSERT_EQ(out.at("calls").size(), 1u);
+    EXPECT_EQ(out.at("calls").at(0).at("args").at(0), "two 2 {\"a\":1}");
+}

+ 675 - 0
runner/tests/job_worker_test.cpp

@@ -0,0 +1,675 @@
+// Tests for the runner-side job worker: the thread(s) that claim cron and
+// database-event jobs and run them through the same RunService the HTTP path
+// uses.
+//
+// There is no queue and no run-log store here. Both reach the database client,
+// which does not compile on every host this targets, so the worker talks to
+// JobQueuePort and RunLogPort and this file implements them in memory - the
+// same seam pattern run_service_test.cpp uses for the registry. The RunService
+// is REAL, including a real QuickJS engine: the thing most worth asserting is
+// that a cron run and an HTTP run go through one engine, and a stubbed runner
+// would assert nothing about that.
+//
+// What is therefore NOT covered here, and has to be covered by the devstack
+// integration pass: FunctionJobQueue's claim CAS (updateIfVersion), the real
+// stale-claim sweep, and FunctionRunLogStore's write and trim.
+#include <gtest/gtest.h>
+
+#include <chrono>
+#include <deque>
+#include <map>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "job_worker.hpp"
+
+using svapi::runner::applyJitter;
+using svapi::runner::buildRunRecord;
+using svapi::runner::buildRunRequest;
+using svapi::runner::classifyException;
+using svapi::runner::classifyOutcome;
+using svapi::runner::composeRunnerId;
+using svapi::runner::FunctionSource;
+using svapi::runner::FunctionView;
+using svapi::runner::idleBackoffMs;
+using svapi::runner::JobDecision;
+using svapi::runner::JobFailure;
+using svapi::runner::JobQueuePort;
+using svapi::runner::JobRunRecord;
+using svapi::runner::JobView;
+using svapi::runner::JobWorker;
+using svapi::runner::JobWorkerOptions;
+using svapi::runner::logTrigger;
+using svapi::runner::makeRunnerId;
+using svapi::runner::ProtocolResponse;
+using svapi::runner::resolveWorkerCount;
+using svapi::runner::retryDelaySec;
+using svapi::runner::RunLogPort;
+using svapi::runner::RunService;
+using svapi::runner::RunServiceOptions;
+
+namespace {
+
+class FakeSource : public FunctionSource {
+public:
+    FunctionView lookup(const std::string& project, const std::string& functionId) override {
+        auto it = rows.find(project + "/" + functionId);
+        if (it == rows.end()) return FunctionView{};
+        return it->second;
+    }
+    void put(const std::string& project, const std::string& id, const std::string& source) {
+        FunctionView v;
+        v.found = true;
+        v.source = source;
+        v.contentHash = "h-" + id + "-" + std::to_string(source.size());
+        v.descriptor = {{"id", id}, {"type", "cron"}, {"schedule", "* * * * *"}};
+        rows[project + "/" + id] = v;
+    }
+    std::map<std::string, FunctionView> rows;
+};
+
+struct CompletedJob {
+    std::string jobId;
+    bool ok = false;
+    std::string error;
+    uint32_t retryAfterSec = 0;
+};
+
+class FakeQueue : public JobQueuePort {
+public:
+    std::optional<JobView> claimNext(const std::string& runnerId) override {
+        std::lock_guard<std::mutex> lock(m);
+        ++claims;
+        claimedBy = runnerId;
+        if (throwOnClaim) throw std::runtime_error("database unreachable");
+        if (pending.empty()) return std::nullopt;
+        JobView job = pending.front();
+        pending.pop_front();
+        return job;
+    }
+    bool complete(const JobView& job, bool ok, const std::string& error,
+                  uint32_t retryAfterSec) override {
+        std::lock_guard<std::mutex> lock(m);
+        completed.push_back({job.jobId, ok, error, retryAfterSec});
+        return !failComplete;
+    }
+    uint32_t reclaimStale(uint32_t, uint32_t) override {
+        std::lock_guard<std::mutex> lock(m);
+        ++sweeps;
+        return 0;
+    }
+
+    size_t completedCount() {
+        std::lock_guard<std::mutex> lock(m);
+        return completed.size();
+    }
+
+    std::mutex m;
+    std::deque<JobView> pending;
+    std::vector<CompletedJob> completed;
+    std::string claimedBy;
+    int claims = 0;
+    int sweeps = 0;
+    bool throwOnClaim = false;
+    bool failComplete = false;
+};
+
+class FakeLog : public RunLogPort {
+public:
+    void record(const std::string& project, const JobRunRecord& entry) override {
+        std::lock_guard<std::mutex> lock(m);
+        entries.push_back({project, entry});
+    }
+    std::mutex m;
+    std::vector<std::pair<std::string, JobRunRecord>> entries;
+};
+
+JobView job(const std::string& id, const std::string& fn, const std::string& trigger = "cron",
+            uint32_t attempts = 1) {
+    JobView j;
+    j.jobId = id;
+    j.project = "p";
+    j.functionId = fn;
+    j.trigger = trigger;
+    j.attempts = attempts;
+    j.payload = {{"at", 1700000000}};
+    return j;
+}
+
+RunServiceOptions serviceOptions() {
+    RunServiceOptions o;
+    o.poolSize = 2;
+    o.limits.wall_time_ms = 1000;
+    o.version = "test";
+    return o;
+}
+
+/// A /run body as RunService produces one, for the classification tests.
+ProtocolResponse runBody(bool ok, int status, const std::string& error, bool timedOut = false,
+                         bool oom = false, bool runnerFault = false) {
+    ProtocolResponse r;
+    r.body = {{"ok", ok},
+              {"status", status},
+              {"headers", nlohmann::json::object()},
+              {"body", nullptr},
+              {"console", nlohmann::json::array()},
+              {"duration_ms", 7},
+              {"error", error},
+              {"runner_fault", runnerFault},
+              {"timed_out", timedOut},
+              {"out_of_memory", oom}};
+    return r;
+}
+
+JobWorkerOptions workerOptions() {
+    JobWorkerOptions o;
+    o.runnerId = "test-runner";
+    o.poolSize = 2;
+    o.workers = 1;
+    o.idleFloorMs = 1;
+    o.idleCeilMs = 2;
+    return o;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------- runner id
+
+TEST(RunnerId, CarriesHostPidAndNonce) {
+    EXPECT_EQ(composeRunnerId("box", 42, "abcd"), "box/42/abcd");
+    // An unresolvable hostname must not produce an id starting with '/', which
+    // would read as an empty host rather than an unknown one.
+    EXPECT_EQ(composeRunnerId("", 42, "abcd"), "unknown/42/abcd");
+}
+
+TEST(RunnerId, DiffersBetweenCallsInOneProcess) {
+    // Same host, same pid: only the nonce can distinguish a restarted runner
+    // from the process whose claim went stale, so it must actually vary.
+    EXPECT_NE(makeRunnerId(), makeRunnerId());
+}
+
+// --------------------------------------------------------------- concurrency
+
+TEST(WorkerCount, NeverExceedsThePool) {
+    // Claiming more jobs than there are runtimes leaves rows claimed while a
+    // thread blocks in acquire(), which burns the stale-claim clock for no
+    // throughput.
+    EXPECT_EQ(resolveWorkerCount(16, 4), 4u);
+    EXPECT_EQ(resolveWorkerCount(2, 4), 2u);
+}
+
+TEST(WorkerCount, DefaultLeavesARuntimeForTheHttpPath) {
+    EXPECT_EQ(resolveWorkerCount(0, 4), 3u);
+    EXPECT_EQ(resolveWorkerCount(0, 1), 1u);  // never zero workers
+    EXPECT_EQ(resolveWorkerCount(0, 0), 1u);  // nor on a nonsense pool size
+}
+
+// ------------------------------------------------------------------ backoff
+
+TEST(IdleBackoff, DoublesFromTheFloorToTheCeiling) {
+    EXPECT_EQ(idleBackoffMs(0, 250, 5000), 250u);
+    EXPECT_EQ(idleBackoffMs(1, 250, 5000), 500u);
+    EXPECT_EQ(idleBackoffMs(2, 250, 5000), 1000u);
+    EXPECT_EQ(idleBackoffMs(4, 250, 5000), 4000u);
+    // The ceiling is the worst-case enqueue-to-pickup latency, and it holds
+    // however long the queue has been empty.
+    EXPECT_EQ(idleBackoffMs(5, 250, 5000), 5000u);
+    EXPECT_EQ(idleBackoffMs(1000, 250, 5000), 5000u);
+}
+
+TEST(IdleBackoff, NeverReturnsZero) {
+    // A zero delay is a busy loop, which is the one thing the backoff exists
+    // to prevent.
+    EXPECT_GT(idleBackoffMs(0, 0, 0), 0u);
+    EXPECT_EQ(idleBackoffMs(3, 300, 100), 300u);  // a ceiling below the floor
+}
+
+TEST(Jitter, SpreadsAroundTheNominalDelay) {
+    EXPECT_EQ(applyJitter(1000, 25, 0.0), 750u);
+    EXPECT_EQ(applyJitter(1000, 25, 0.5), 1000u);
+    EXPECT_NEAR(applyJitter(1000, 25, 1.0), 1250u, 1);
+    EXPECT_EQ(applyJitter(1000, 0, 0.0), 1000u);  // disabled means unchanged
+    EXPECT_GT(applyJitter(1, 25, 0.0), 0u);
+}
+
+TEST(RetryDelay, TriplesAndCaps) {
+    EXPECT_EQ(retryDelaySec(1, 5, 300), 5u);
+    EXPECT_EQ(retryDelaySec(2, 5, 300), 15u);
+    EXPECT_EQ(retryDelaySec(3, 5, 300), 45u);
+    EXPECT_EQ(retryDelaySec(4, 5, 300), 135u);
+    EXPECT_EQ(retryDelaySec(5, 5, 300), 300u);
+    EXPECT_EQ(retryDelaySec(50, 5, 300), 300u);
+}
+
+// ------------------------------------------------------------- log mapping
+
+TEST(LogTrigger, IsAClosedSet) {
+    EXPECT_EQ(logTrigger("cron"), "cron");
+    EXPECT_EQ(logTrigger("db"), "db");
+    // A corrupt row cannot write arbitrary text into a column the UI renders
+    // as a label.
+    EXPECT_EQ(logTrigger(""), "job");
+    EXPECT_EQ(logTrigger("<script>"), "job");
+}
+
+TEST(RunRecord, CarriesWhatTheHttpPathCarries) {
+    ProtocolResponse r = runBody(true, 201, "");
+    r.body["duration_ms"] = 12;
+    r.body["console"] = nlohmann::json::array({"hello", 7});
+    r.body["headers"] = {{"x-a", "b"}};
+    JobDecision d;
+    d.ok = true;
+    d.status = 201;
+
+    const JobRunRecord e = buildRunRecord(job("j1", "f"), "run-1", 1700000001, r.body, d);
+    EXPECT_EQ(e.runId, "run-1");
+    EXPECT_EQ(e.functionId, "f");
+    EXPECT_EQ(e.trigger, "cron");
+    EXPECT_TRUE(e.ok);
+    EXPECT_EQ(e.status, 201);
+    EXPECT_EQ(e.durationMs, 12);
+    EXPECT_EQ(e.startedAt, 1700000001u);
+    ASSERT_EQ(e.console.size(), 1u);  // a non-string console line is dropped, not stringified
+    EXPECT_EQ(e.console[0], "hello");
+    EXPECT_EQ(e.headers.value("x-a", ""), "b");
+}
+
+TEST(RunRecord, SurvivesAnEmptyBody) {
+    JobDecision d;
+    d.error = "boom";
+    const JobRunRecord e =
+        buildRunRecord(job("j1", "f", "db"), "run-1", 5, nlohmann::json::object(), d);
+    EXPECT_EQ(e.trigger, "db");
+    EXPECT_FALSE(e.ok);
+    EXPECT_EQ(e.durationMs, 0);
+    EXPECT_EQ(e.error, "boom");
+    EXPECT_TRUE(e.console.empty());
+}
+
+TEST(RunRequest, PassesThePayloadAsTheTrigger) {
+    const nlohmann::json req = buildRunRequest(job("j1", "f"));
+    EXPECT_EQ(req.value("project", ""), "p");
+    EXPECT_EQ(req.value("function_id", ""), "f");
+    ASSERT_TRUE(req.at("trigger").is_object());
+    EXPECT_EQ(req.at("trigger").value("at", 0), 1700000000);
+    EXPECT_EQ(req.at("trigger").value("type", ""), "cron");
+}
+
+TEST(RunRequest, NeverOverwritesThePayloadsOwnType) {
+    JobView j = job("j1", "f");
+    j.payload = {{"type", "insert"}, {"collection", "c"}};
+    const nlohmann::json req = buildRunRequest(j);
+    EXPECT_EQ(req.at("trigger").value("type", ""), "insert");
+}
+
+// ------------------------------------------------- the retry classification
+
+TEST(Classify, SuccessIsDoneWhateverStatusTheFunctionChose) {
+    const JobWorkerOptions o = workerOptions();
+    // There is no HTTP client for a cron run, so a function that deliberately
+    // returns 500 has still done its job and must not be re-run.
+    for (int status : {200, 204, 404, 500}) {
+        const JobDecision d = classifyOutcome(runBody(true, status, ""), job("j", "f"), o);
+        EXPECT_EQ(d.failure, JobFailure::None);
+        EXPECT_TRUE(d.ok);
+        EXPECT_EQ(d.retryAfterSec, 0u);
+        EXPECT_EQ(d.status, status);
+    }
+}
+
+TEST(Classify, AThrowingFunctionIsNeverRetried) {
+    // It will throw again. A retry costs a queue slot, a runtime lease and a
+    // wall-time budget to learn nothing.
+    const JobDecision d =
+        classifyOutcome(runBody(false, 500, "TypeError: x is not a function"), job("j", "f"),
+                        workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::FunctionFault);
+    EXPECT_FALSE(d.ok);
+    EXPECT_EQ(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, StoredBrokennessIsNeverRetried) {
+    const JobWorkerOptions o = workerOptions();
+    for (int status : {409, 422}) {
+        const JobDecision d = classifyOutcome(runBody(false, status, "nope"), job("j", "f"), o);
+        EXPECT_EQ(d.failure, JobFailure::FunctionFault) << status;
+        EXPECT_EQ(d.retryAfterSec, 0u) << status;
+    }
+}
+
+TEST(Classify, OutOfMemoryIsNeverRetried) {
+    const JobDecision d = classifyOutcome(runBody(false, 500, "out of memory", false, true),
+                                          job("j", "f"), workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::FunctionFault);
+    EXPECT_EQ(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, ATimeoutIsAFunctionFaultUnlessConfiguredOtherwise) {
+    JobWorkerOptions o = workerOptions();
+    JobDecision d = classifyOutcome(runBody(false, 504, "timed out", true), job("j", "f"), o);
+    EXPECT_EQ(d.failure, JobFailure::FunctionFault);
+    EXPECT_EQ(d.retryAfterSec, 0u);
+
+    o.retryTimeouts = true;
+    d = classifyOutcome(runBody(false, 504, "timed out", true), job("j", "f"), o);
+    EXPECT_EQ(d.failure, JobFailure::RunnerFault);
+    EXPECT_GT(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, NoRuntimeAvailableIsRetried) {
+    // Nothing of the function ran, so nothing was decided about it.
+    const JobDecision d = classifyOutcome(runBody(false, 503, "no runtime available"),
+                                          job("j", "f"), workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::RunnerFault);
+    EXPECT_EQ(d.retryAfterSec, 5u);
+}
+
+TEST(Classify, AHostContextFailureIsRetriedDespiteBeingA500) {
+    // The database was briefly away; the function is blameless. /run says so
+    // with `runner_fault`, so this no longer depends on the error wording - a
+    // reworded message used to silently turn a retryable blip into a permanent
+    // failure.
+    const JobDecision d = classifyOutcome(
+        runBody(false, 500, "host bindings unavailable: db read failed", false, false,
+                /*runnerFault*/ true),
+        job("j", "f"), workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::RunnerFault);
+    EXPECT_GT(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, AThrowStaysTheFunctionsFaultEvenWhenItMentionsTheRunner) {
+    // The flag, not the text: a function free to throw any message it likes
+    // must not be able to talk its way into being retried.
+    const JobDecision d =
+        classifyOutcome(runBody(false, 500, "Error: host bindings unavailable"), job("j", "f"),
+                        workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::FunctionFault);
+    EXPECT_EQ(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, ATransportLevelFailureIsRetried) {
+    ProtocolResponse r;
+    r.httpStatus = 503;
+    r.body = {{"ok", false}, {"error", "no runtime available"}};
+    const JobDecision d = classifyOutcome(r, job("j", "f"), workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::RunnerFault);
+    EXPECT_GT(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, AMalformedRequestIsOurBugAndIsNotRetried) {
+    ProtocolResponse r;
+    r.httpStatus = 400;
+    r.body = {{"ok", false}, {"error", "'function_id' is required"}};
+    const JobDecision d = classifyOutcome(r, job("j", "f"), workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::Malformed);
+    EXPECT_EQ(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, NotFoundIsRetriedButBounded) {
+    JobWorkerOptions o = workerOptions();
+    o.lookupRetryAttempts = 3;
+    // 404 also means "the registry read failed", because FunctionView has no
+    // third answer. Bounded retries survive a database blink without keeping a
+    // deleted function's jobs circulating.
+    JobDecision d = classifyOutcome(runBody(false, 404, "not found"), job("j", "f", "cron", 1), o);
+    EXPECT_EQ(d.failure, JobFailure::TransientLookup);
+    EXPECT_EQ(d.retryAfterSec, 5u);
+
+    d = classifyOutcome(runBody(false, 404, "not found"), job("j", "f", "cron", 3), o);
+    EXPECT_EQ(d.failure, JobFailure::TransientLookup);
+    EXPECT_EQ(d.retryAfterSec, 0u);  // budget spent: failed outright
+    EXPECT_NE(d.error.find("giving up"), std::string::npos);
+}
+
+TEST(Classify, AnyRetryStopsAtMaxAttempts) {
+    JobWorkerOptions o = workerOptions();
+    o.maxAttempts = 3;
+    const JobDecision d = classifyOutcome(runBody(false, 503, "no runtime available"),
+                                          job("j", "f", "cron", 3), o);
+    EXPECT_EQ(d.failure, JobFailure::RunnerFault);
+    EXPECT_EQ(d.retryAfterSec, 0u);
+}
+
+TEST(Classify, AnExceptionOutOfTheServiceIsRetried) {
+    const JobDecision d = classifyException("bad_alloc", job("j", "f"), workerOptions());
+    EXPECT_EQ(d.failure, JobFailure::RunnerFault);
+    EXPECT_GT(d.retryAfterSec, 0u);
+    EXPECT_EQ(d.error, "bad_alloc");
+}
+
+// --------------------------------------------- one cycle, with a real engine
+
+TEST(RunOnce, RunsTheJobThroughRunServiceAndLogsIt) {
+    FakeSource source;
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async (ctx) => { console.log('tick ' + ctx.at); "
+               "return { status: 202, body: { seen: ctx.type } }; };\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", "f"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    EXPECT_EQ(queue.claimedBy, "test-runner");
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_TRUE(queue.completed[0].ok);
+    EXPECT_EQ(queue.completed[0].retryAfterSec, 0u);
+
+    // A scheduled run has to be as visible as an invoked one: nothing else ever
+    // sees this output.
+    ASSERT_EQ(log.entries.size(), 1u);
+    EXPECT_EQ(log.entries[0].first, "p");
+    EXPECT_EQ(log.entries[0].second.trigger, "cron");
+    EXPECT_EQ(log.entries[0].second.status, 202);
+    EXPECT_TRUE(log.entries[0].second.ok);
+    ASSERT_EQ(log.entries[0].second.console.size(), 1u);
+    EXPECT_EQ(log.entries[0].second.console[0], "tick 1700000000");
+    EXPECT_FALSE(log.entries[0].second.runId.empty());
+    EXPECT_EQ(worker.stats().succeeded, 1u);
+}
+
+TEST(RunOnce, AThrowingFunctionIsLoggedAndFailedOutright) {
+    FakeSource source;
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async () => { throw new Error('nope'); };\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", "f"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_FALSE(queue.completed[0].ok);
+    EXPECT_EQ(queue.completed[0].retryAfterSec, 0u);
+    EXPECT_NE(queue.completed[0].error.find("nope"), std::string::npos);
+    ASSERT_EQ(log.entries.size(), 1u);
+    EXPECT_EQ(log.entries[0].second.status, 500);
+    EXPECT_EQ(worker.stats().failed, 1u);
+}
+
+TEST(RunOnce, AMissingFunctionIsRetried) {
+    FakeSource source;  // nothing registered
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", "gone"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_FALSE(queue.completed[0].ok);
+    EXPECT_GT(queue.completed[0].retryAfterSec, 0u);
+    EXPECT_EQ(worker.stats().retried, 1u);
+}
+
+TEST(RunOnce, AnEmptyQueueIsNotAnError) {
+    FakeSource source;
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_FALSE(worker.runOnce());
+    EXPECT_TRUE(queue.completed.empty());
+    EXPECT_TRUE(log.entries.empty());
+}
+
+TEST(RunOnce, AFailedClaimTakesNothingAndCompletesNothing) {
+    FakeSource source;
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.throwOnClaim = true;
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_FALSE(worker.runOnce());  // backing off is the whole response
+    EXPECT_EQ(worker.stats().claimed, 0u);
+    EXPECT_TRUE(queue.completed.empty());
+}
+
+TEST(RunOnce, ARowWithNoFunctionIdFailsWithoutCallingTheEngine) {
+    FakeSource source;
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    JobView bad = job("j1", "");
+    queue.pending.push_back(bad);
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    ASSERT_EQ(queue.completed.size(), 1u);
+    EXPECT_FALSE(queue.completed[0].ok);
+    EXPECT_EQ(queue.completed[0].retryAfterSec, 0u);
+    // No function id means no per-function log row to write.
+    EXPECT_TRUE(log.entries.empty());
+}
+
+TEST(RunOnce, AFailedCompleteIsCountedBecauseTheJobWillRunTwice) {
+    FakeSource source;
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async () => ({ body: 'ok' });\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.failComplete = true;
+    queue.pending.push_back(job("j1", "f"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    EXPECT_TRUE(worker.runOnce());
+    EXPECT_EQ(worker.stats().completeFailures, 1u);
+    // The log was written before the queue was told, so the attempt that did
+    // happen is on record even though the row will come back.
+    EXPECT_EQ(log.entries.size(), 1u);
+}
+
+// -------------------------------------------------------- threads, shutdown
+
+TEST(Threads, DrainsTheQueueAndStopsCleanly) {
+    FakeSource source;
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async () => ({ body: 'ok' });\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    for (int i = 0; i < 6; ++i) queue.pending.push_back(job("j" + std::to_string(i), "f"));
+
+    JobWorkerOptions options = workerOptions();
+    options.workers = 2;
+    JobWorker worker(service, queue, log, options);
+    worker.start();
+    const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
+    while (queue.completedCount() < 6 && std::chrono::steady_clock::now() < deadline)
+        std::this_thread::sleep_for(std::chrono::milliseconds(5));
+    worker.stop();   // joins; a second stop must be a no-op
+    worker.stop();
+
+    EXPECT_EQ(queue.completedCount(), 6u);
+    EXPECT_EQ(worker.stats().succeeded, 6u);
+    for (const CompletedJob& c : queue.completed) EXPECT_TRUE(c.ok) << c.jobId;
+}
+
+TEST(Threads, StopDoesNotWaitOutTheIdleBackoff) {
+    FakeSource source;
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    JobWorkerOptions options = workerOptions();
+    options.idleFloorMs = 30000;  // an empty queue parks the thread for 30s
+    options.idleCeilMs = 30000;
+    options.jitterPercent = 0;
+    JobWorker worker(service, queue, log, options);
+
+    worker.start();
+    std::this_thread::sleep_for(std::chrono::milliseconds(50));
+    const auto t0 = std::chrono::steady_clock::now();
+    worker.stop();
+    const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                             std::chrono::steady_clock::now() - t0)
+                             .count();
+    // Shutdown has to be prompt: systemd's stop timeout is not 30 seconds.
+    EXPECT_LT(elapsed, 2000);
+}
+
+TEST(Threads, AJobInFlightIsFinishedRatherThanAbandoned) {
+    FakeSource source;
+    // Long enough that stop() is certainly called mid-run, short enough to stay
+    // inside the configured wall-time ceiling.
+    source.put("p", "f",
+               "export const on = { id: 'f', type: 'cron', schedule: '* * * * *' };\n"
+               "export default async () => { const t = Date.now(); "
+               "while (Date.now() - t < 300) {} return { body: 'done' }; };\n");
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    queue.pending.push_back(job("j1", "f"));
+    JobWorker worker(service, queue, log, workerOptions());
+
+    worker.start();
+    std::this_thread::sleep_for(std::chrono::milliseconds(60));
+    worker.stop();
+
+    // Finishing is strictly better than being killed and re-run by the stale
+    // sweeper: the outcome is recorded, so the job is not repeated.
+    ASSERT_EQ(queue.completedCount(), 1u);
+    EXPECT_TRUE(queue.completed[0].ok);
+    EXPECT_EQ(log.entries.size(), 1u);
+}
+
+TEST(Threads, TheStaleSweepIsOffUnlessAnIntervalIsSet) {
+    FakeSource source;
+    RunService service(source, serviceOptions());
+    FakeQueue queue;
+    FakeLog log;
+    JobWorkerOptions options = workerOptions();
+    options.idleFloorMs = 10;
+    options.idleCeilMs = 10;
+    {
+        // vectorapi is the singleton that owns queue maintenance; N runners all
+        // sweeping is wasted queries, so a runner only sweeps when told to.
+        JobWorker worker(service, queue, log, options);
+        worker.start();
+        std::this_thread::sleep_for(std::chrono::milliseconds(80));
+        worker.stop();
+    }
+    EXPECT_EQ(queue.sweeps, 0);
+
+    options.reclaimIntervalSec = 1;
+    options.jitterPercent = 90;  // keeps the first sweep well inside the wait below
+    {
+        JobWorker worker(service, queue, log, options);
+        worker.start();
+        const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
+        while (queue.sweeps == 0 && std::chrono::steady_clock::now() < deadline)
+            std::this_thread::sleep_for(std::chrono::milliseconds(20));
+        worker.stop();
+    }
+    EXPECT_GT(queue.sweeps, 0);
+}

+ 3 - 4
runner/tests/js_runtime_test.cpp

@@ -1,8 +1,7 @@
 // Tests for the QuickJS execution core. These are the executable form of the
 // safety contract in docs/superpowers/specs/2026-10-06-function-runtime-design.md
 // ("Safety"): per-run limits, a fresh context per run, nothing leaking between
-// tenants. They must stay runnable on the dev host, so nothing here touches the
-// database client.
+// tenants. Nothing here touches the database client.
 #include <gtest/gtest.h>
 
 #include <atomic>
@@ -315,7 +314,7 @@ TEST(JsRuntime, NoHostGlobalsAreExposed) {
 
 // QuickJS accounts every allocation it makes, so a JSValue this code forgets to
 // free shows up as a runtime whose footprint climbs run after run. That is the
-// only leak detector available on the dev host (no sanitizer runtimes), so it
+// only leak detector that needs no sanitizer runtime, so it
 // is worth a test of its own.
 TEST(JsRuntime, RepeatedRunsDoNotLeakRuntimeMemory) {
     JsRuntime rt;
@@ -502,7 +501,7 @@ TEST(JsRuntimePool, RetiresARuntimeLeftWithPendingJobs) {
         // bounded flush is a race against how many were queued when the
         // deadline passed, and it resolves differently on a faster machine.
         // Both outcomes are safe, and asserting one of them made this test fail
-        // in the Debian build container while passing on the dev host. What
+        // on one machine while passing on another. What
         // must hold either way is below: the NEXT tenant sees a clean runtime.
         poisonedAfterTimeout = lease->poisoned();
     }

+ 267 - 1
runner/tests/run_service_test.cpp

@@ -70,7 +70,12 @@ nlohmann::json runRequest(const std::string& id = "f") {
 RunServiceOptions fastOptions() {
     RunServiceOptions o;
     o.poolSize = 2;
+    // All three, because they are three different ceilings now: the engine's
+    // hard one and one per kind of run. A test that set only the first would
+    // still be measured against the 2s/120s defaults.
     o.limits.wall_time_ms = 1000;
+    o.httpWallCeilingMs = 1000;
+    o.jobWallCeilingMs = 1000;
     return o;
 }
 
@@ -271,7 +276,7 @@ TEST(RunServiceFailure, TheDescriptorTimeoutCannotRaiseTheConfiguredCeiling) {
     // clamped this test would take 5s instead of ~0.12s.
     src.put("p", "f", httpFunction("export default function () { for (;;) {} }", 5000));
     RunServiceOptions o = fastOptions();
-    o.limits.wall_time_ms = 120;
+    o.httpWallCeilingMs = 120;
     RunService svc(src, o);
 
     ProtocolResponse r = svc.run(runRequest());
@@ -288,6 +293,7 @@ TEST(RunServiceFailure, AMemoryBreachIs500AndFlagsOutOfMemory) {
     RunServiceOptions o = fastOptions();
     o.limits.memory_limit_bytes = 2u * 1024 * 1024;
     o.limits.wall_time_ms = 5000;
+    o.httpWallCeilingMs = 5000;
     RunService svc(src, o);
 
     ProtocolResponse r = svc.run(runRequest());
@@ -501,3 +507,263 @@ TEST(RunServiceHealth, ReportsThePoolAndIsAlways200) {
     EXPECT_TRUE(r.body.at("pool").contains("idle"));
     EXPECT_TRUE(r.body.at("pool").contains("retired"));
 }
+
+// ------------------------------------------------------------- wall budget
+//
+// The resolver is where the whole behaviour lives: four inputs and a
+// precedence order. Tested directly, because asserting precedence through a
+// run means asserting it with a stopwatch.
+
+using svapi::functions::parseRunKind;
+using svapi::functions::resolveWallBudget;
+using svapi::functions::RunKind;
+using svapi::functions::WallBudgetRequest;
+
+namespace {
+
+WallBudgetRequest budgetRequest() {
+    WallBudgetRequest r;
+    r.httpCeilingMs = 2000;
+    r.jobCeilingMs = 120000;
+    r.hardCeilingMs = 120000;
+    return r;
+}
+
+} // namespace
+
+TEST(WallBudget, AnUndeclaredRunGetsTheCeilingForItsKind) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Http;
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 2000);
+    r.kind = RunKind::Job;
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 120000);
+}
+
+TEST(WallBudget, TheDeclaredTimeoutIsHonouredUpToTheKindCeiling) {
+    WallBudgetRequest r = budgetRequest();
+    r.declaredMs = 120000;
+
+    // The bug this change exists to fix: an LLM call asking for two minutes.
+    r.kind = RunKind::Job;
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 120000);
+    EXPECT_FALSE(resolveWallBudget(r).clampedByCeiling);
+
+    // The same descriptor over HTTP still gets two seconds, and says so.
+    r.kind = RunKind::Http;
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 2000);
+    EXPECT_TRUE(resolveWallBudget(r).clampedByCeiling);
+    EXPECT_FALSE(resolveWallBudget(r).clampedByProjectMax);
+}
+
+TEST(WallBudget, ADeclaredTimeoutBelowTheCeilingNarrows) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Job;
+    r.declaredMs = 5000;
+    const auto b = resolveWallBudget(r);
+    EXPECT_EQ(b.effectiveMs, 5000);
+    EXPECT_FALSE(b.clampedByCeiling);
+}
+
+TEST(WallBudget, TheConfiguredDefaultAppliesOnlyWhenNothingIsDeclared) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Job;
+    r.defaultMs = 3000;
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 3000);
+
+    r.declaredMs = 30000;
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 30000);
+}
+
+TEST(WallBudget, TheProjectMaximumNarrowsAndIsReportedSeparately) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Job;
+    r.declaredMs = 120000;
+    r.projectMaxMs = 10000;
+
+    const auto b = resolveWallBudget(r);
+    EXPECT_EQ(b.effectiveMs, 10000);
+    EXPECT_TRUE(b.clampedByProjectMax);
+    // Which cap bound the run decides who can raise it, so the two flags are
+    // not interchangeable.
+    EXPECT_FALSE(b.clampedByCeiling);
+}
+
+TEST(WallBudget, AProjectMaximumCanNeverRaiseACeiling) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Http;
+    r.declaredMs = 60000;
+    r.projectMaxMs = 600000;
+
+    const auto b = resolveWallBudget(r);
+    EXPECT_EQ(b.effectiveMs, 2000);
+    EXPECT_TRUE(b.clampedByCeiling);
+    EXPECT_FALSE(b.clampedByProjectMax);
+}
+
+TEST(WallBudget, AProjectMaximumAlsoCapsAnUndeclaredRun) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Job;
+    r.projectMaxMs = 7000;
+
+    const auto b = resolveWallBudget(r);
+    EXPECT_EQ(b.effectiveMs, 7000);
+    // Nothing was requested, so nothing was clamped: the cap IS the budget.
+    EXPECT_FALSE(b.clampedByProjectMax);
+    EXPECT_FALSE(b.clampedByCeiling);
+}
+
+TEST(WallBudget, TheHardCeilingBindsEvenWhenAKindCeilingIsHigher) {
+    WallBudgetRequest r = budgetRequest();
+    r.kind = RunKind::Job;
+    r.jobCeilingMs = 600000;
+    r.hardCeilingMs = 90000;
+    r.declaredMs = 600000;
+
+    const auto b = resolveWallBudget(r);
+    EXPECT_EQ(b.effectiveMs, 90000);
+    EXPECT_EQ(b.ceilingMs, 90000);
+}
+
+TEST(WallBudget, NothingConfiguredFallsBackRatherThanGrantingForever) {
+    WallBudgetRequest r;  // every ceiling 0
+    r.declaredMs = 120000;
+    const auto b = resolveWallBudget(r);
+    EXPECT_EQ(b.effectiveMs, svapi::functions::kFallbackWallCeilingMs);
+    EXPECT_TRUE(b.clampedByCeiling);
+}
+
+TEST(WallBudget, ABudgetIsNeverZeroOrNegative) {
+    WallBudgetRequest r = budgetRequest();
+    r.projectMaxMs = -5;        // ignored: a cap must be positive to be a cap
+    r.declaredMs = -1;          // ignored: treated as "not declared"
+    EXPECT_EQ(resolveWallBudget(r).effectiveMs, 2000);
+}
+
+TEST(WallBudget, AnUnknownKindOnTheWireMeansHttp) {
+    EXPECT_EQ(parseRunKind("job", RunKind::Http), RunKind::Job);
+    EXPECT_EQ(parseRunKind("http", RunKind::Job), RunKind::Http);
+    // Not "Job", not a throw: the short budget is the safe guess, and a typo
+    // in a caller must not hand out two minutes of a shared runtime.
+    EXPECT_EQ(parseRunKind("JOB", RunKind::Http), RunKind::Http);
+    EXPECT_EQ(parseRunKind("", RunKind::Http), RunKind::Http);
+    EXPECT_EQ(parseRunKind("cron", RunKind::Http), RunKind::Http);
+}
+
+// ------------------------------------------------- the budget through /run
+
+TEST(RunServiceBudget, TheSameFunctionGetsDifferentBudgetsPerKind) {
+    FakeSource src;
+    src.put("p", "f",
+            httpFunction("export default function () { return { body: 'ok' }; }", 120000));
+    RunServiceOptions o;
+    o.poolSize = 2;
+    o.httpWallCeilingMs = 2000;
+    o.jobWallCeilingMs = 120000;
+    RunService svc(src, o);
+
+    const ProtocolResponse http = svc.run(runRequest(), RunKind::Http);
+    EXPECT_EQ(http.body.at("run_kind"), "http");
+    EXPECT_EQ(http.body.at("wall_budget_ms"), 2000);
+
+    const ProtocolResponse job = svc.run(runRequest(), RunKind::Job);
+    EXPECT_EQ(job.body.at("run_kind"), "job");
+    EXPECT_EQ(job.body.at("wall_budget_ms"), 120000);
+}
+
+TEST(RunServiceBudget, TheKindDefaultsToHttpWhenACallerDoesNotSay) {
+    FakeSource src;
+    src.put("p", "f",
+            httpFunction("export default function () { return { body: 'ok' }; }", 120000));
+    RunServiceOptions o;
+    o.poolSize = 1;
+    o.httpWallCeilingMs = 2000;
+    o.jobWallCeilingMs = 120000;
+    RunService svc(src, o);
+
+    // Fail-safe: a forgotten argument costs a slow run, not a two-minute lease
+    // on a pooled runtime.
+    EXPECT_EQ(svc.run(runRequest()).body.at("wall_budget_ms"), 2000);
+}
+
+TEST(RunServiceBudget, AJobCeilingIsNotKilledByTheEnginesHardLimit) {
+    FunctionView v =
+        httpFunction("export default function () { return { body: 'ok' }; }", 90000);
+    FakeSource src;
+    src.put("p", "f", v);
+    RunServiceOptions o;
+    o.poolSize = 1;
+    // An operator who only set the old single ceiling: the engine's hard limit
+    // must be raised to the job ceiling, or every job run dies at 2s.
+    o.limits.wall_time_ms = 2000;
+    o.httpWallCeilingMs = 2000;
+    o.jobWallCeilingMs = 120000;
+    RunService svc(src, o);
+
+    EXPECT_EQ(svc.run(runRequest(), RunKind::Job).body.at("wall_budget_ms"), 90000);
+    EXPECT_EQ(svc.health().body.at("wall_time_ms").at("hard"), 120000);
+}
+
+TEST(RunServiceBudget, TheProjectMaximumFromTheRegistrySeamApplies) {
+    FunctionView v =
+        httpFunction("export default function () { return { body: 'ok' }; }", 120000);
+    v.projectMaxWallTimeMs = 4000;
+    FakeSource src;
+    src.put("p", "f", v);
+    RunServiceOptions o;
+    o.poolSize = 1;
+    o.httpWallCeilingMs = 2000;
+    o.jobWallCeilingMs = 120000;
+    RunService svc(src, o);
+
+    const ProtocolResponse r = svc.run(runRequest(), RunKind::Job);
+    EXPECT_EQ(r.body.at("wall_budget_ms"), 4000);
+    // The clamp is said out loud in the run's own console, or the author reads
+    // a timeout with no cause.
+    ASSERT_TRUE(r.body.at("console").is_array());
+    ASSERT_FALSE(r.body.at("console").empty());
+    const std::string first = r.body.at("console").at(0).get<std::string>();
+    EXPECT_NE(first.find("project's maximum"), std::string::npos) << first;
+}
+
+TEST(RunServiceBudget, AJobRunActuallyOutlivesTheHttpCeiling) {
+    FakeSource src;
+    // Busy-waits past the HTTP ceiling but well inside the job ceiling. The
+    // point of the whole change: this function is impossible over HTTP and
+    // ordinary on cron.
+    src.put("p", "f",
+            httpFunction("export default function () {"
+                         "  const until = Date.now() + 180;"
+                         "  while (Date.now() < until) {}"
+                         "  return { body: 'done' };"
+                         "}",
+                         3000));
+    RunServiceOptions o;
+    o.poolSize = 1;
+    o.httpWallCeilingMs = 80;
+    o.jobWallCeilingMs = 3000;
+    RunService svc(src, o);
+
+    const ProtocolResponse http = svc.run(runRequest(), RunKind::Http);
+    EXPECT_TRUE(http.body.at("timed_out").get<bool>()) << http.body.dump();
+    EXPECT_EQ(http.body.at("status"), 504);
+
+    const ProtocolResponse job = svc.run(runRequest(), RunKind::Job);
+    EXPECT_FALSE(job.body.at("timed_out").get<bool>()) << job.body.dump();
+    EXPECT_EQ(job.body.at("body"), "done");
+}
+
+TEST(RunServiceHealth, ReportsBothCeilings) {
+    FakeSource src;
+    RunServiceOptions o;
+    o.poolSize = 1;
+    o.httpWallCeilingMs = 1500;
+    o.jobWallCeilingMs = 60000;
+    o.defaultTimeoutMs = 700;
+    RunService svc(src, o);
+
+    const nlohmann::json wall = svc.health().body.at("wall_time_ms");
+    EXPECT_EQ(wall.at("http"), 1500);
+    EXPECT_EQ(wall.at("job"), 60000);
+    EXPECT_EQ(wall.at("hard"), 60000);
+    EXPECT_EQ(wall.at("default"), 700);
+}

+ 8 - 0
src/CMakeLists.txt

@@ -14,9 +14,14 @@ add_library(vectorapi_core STATIC
     key_store.cpp
     settings_store.cpp
     collection_registry.cpp
+    function_jobs.cpp
     function_record.cpp
     function_registry.cpp
     function_run_log.cpp
+    function_scheduler.cpp
+    function_events.cpp
+    project_secrets.cpp
+    project_secret_store.cpp
     runner_client.cpp
     embeddings.cpp
     embedding_cache.cpp
@@ -35,9 +40,12 @@ add_library(vectorapi_core STATIC
     handlers/stats.cpp
     handlers/settings.cpp
     handlers/project_settings.cpp
+    handlers/project_secrets.cpp
     handlers/relations.cpp
     handlers/functions.cpp
     handlers/function_dispatch.cpp
+    functions/cron.cpp
+    functions/timezone.cpp
     functions/descriptor.cpp
     functions/net_guard.cpp
 )

+ 19 - 1
src/config.cpp

@@ -19,7 +19,7 @@ Config Config::fromJson(const nlohmann::json& j) {
         const auto& f = j["functions"];
         if (f.contains("runners") && f["runners"].is_array()) {
             // Bind before iterating: a range-for over a temporary subobject of a
-            // parsed document dangles (see CLAUDE.md).
+            // parsed document dangles.
             const nlohmann::json& runners = f["runners"];
             for (const auto& e : runners)
                 if (e.is_string() && !e.get<std::string>().empty())
@@ -27,6 +27,24 @@ Config Config::fromJson(const nlohmann::json& j) {
         }
         c.functionRunsKept = f.value("runs_kept", c.functionRunsKept);
         c.runnerToken = f.value("runner_token", c.runnerToken);
+        if (f.contains("scheduler") && f["scheduler"].is_object()) {
+            const auto& s = f["scheduler"];
+            c.schedulerEnabled   = s.value("enabled", c.schedulerEnabled);
+            c.schedulerTickSec   = s.value("tick_interval_sec", c.schedulerTickSec);
+            c.reclaimIntervalSec = s.value("reclaim_interval_sec", c.reclaimIntervalSec);
+        }
+        if (f.contains("jobs") && f["jobs"].is_object()) {
+            const auto& j2 = f["jobs"];
+            c.claimTimeoutSec = j2.value("claim_timeout_sec", c.claimTimeoutSec);
+            c.jobMaxAttempts  = j2.value("max_attempts", c.jobMaxAttempts);
+        }
+        if (f.contains("events") && f["events"].is_object()) {
+            const auto& e = f["events"];
+            c.eventsEnabled    = e.value("enabled", c.eventsEnabled);
+            c.eventsMaxDepth   = e.value("max_depth", c.eventsMaxDepth);
+            c.eventsRefreshSec = e.value("refresh_interval_sec", c.eventsRefreshSec);
+            c.eventsMaxPending = e.value("max_pending", c.eventsMaxPending);
+        }
     }
     return c;
 }

+ 19 - 0
src/config.hpp

@@ -28,6 +28,25 @@ struct Config {
     /// world-readable. Empty is valid only for a loopback runner.
     std::string runnerToken;
 
+    /// The cron scheduler and the database-event watcher. Both live here rather
+    /// than in the runner because there must be exactly ONE of each: N runners
+    /// each firing every cron is the obvious bug.
+    ///
+    /// Enabled only when runners are configured, because a queue nobody drains
+    /// is worse than no queue - jobs would pile up looking like work in
+    /// progress.
+    bool     schedulerEnabled   = true;
+    uint32_t schedulerTickSec   = 20;   ///< must stay under 60 or whole cron minutes are missed
+    uint32_t reclaimIntervalSec = 60;
+    /// Must exceed the runner's job wall-time ceiling, or a healthy long run
+    /// gets reclaimed and executed a second time.
+    uint32_t claimTimeoutSec    = 300;
+    uint32_t jobMaxAttempts     = 3;
+    bool     eventsEnabled      = true;
+    uint32_t eventsMaxDepth     = 3;
+    uint32_t eventsRefreshSec   = 15;
+    uint32_t eventsMaxPending   = 2048;
+
     static Config fromJson(const nlohmann::json& j);
     static Config load(const std::string& path);  // reads file then fromJson
 };

+ 70 - 12
src/db_errors.cpp

@@ -10,7 +10,11 @@ using Code = smartbotic::database::Client::ErrorCode;
 /// `duplicate_values` deliberately matches what POST /indexes already returns
 /// for the same condition, so a caller sees one slug for "this value is taken"
 /// however it was hit.
-ApiError translate(Code code, const std::string& message, const std::string& notFoundMessage) {
+/// `reason` is what disambiguates FailedPrecondition, which the database uses
+/// for three unrelated refusals. Empty means an older server, or a
+/// FailedPrecondition raised somewhere that does not set one.
+ApiError translate(Code code, const std::string& message, const std::string& notFoundMessage,
+                   const std::string& reason, const nlohmann::json& details) {
     switch (code) {
         // The call reported failure but the database raised nothing: on
         // update/patch/remove that means the document was simply not there.
@@ -18,11 +22,26 @@ ApiError translate(Code code, const std::string& message, const std::string& not
         case Code::Ok:
             return ApiError(ErrCode::NotFound, "not_found", notFoundMessage);
         case Code::AlreadyExists:
-            return ApiError(ErrCode::Conflict, "duplicate_values", message);
+            // `details` carries the field that collided and the colliding
+            // value, straight from the database. This used to be recovered by
+            // taking the error SENTENCE apart, which broke the moment anyone
+            // reworded it.
+            return ApiError(ErrCode::Conflict, "duplicate_values", message, details);
         case Code::FailedPrecondition:
-            // A child pointing at a parent that does not exist, or a delete a
-            // restrict relation refuses. The caller can fix both.
-            return ApiError(ErrCode::Unprocessable, "relation_violation", message);
+            // THREE unrelated refusals share this code, and they are not the
+            // same answer. Mapping the bare code to 422 told a caller that a
+            // read-only database was its own validation mistake - so it would
+            // fix its payload and retry forever instead of waiting.
+            if (reason == "missing_parent" || reason == "delete_restricted")
+                return ApiError(ErrCode::Unprocessable, "relation_violation", message, details);
+            if (reason == "read_only")
+                // Not the caller's fault and not permanent: it waits.
+                return ApiError(ErrCode::Unavailable, "read_only", message, details);
+            // An unrecognised or absent reason is NOT assumed to be a relation
+            // violation. We do not know what refused this, and saying "your
+            // request is invalid" when we cannot tell is worse than admitting
+            // it is ours.
+            return ApiError(ErrCode::Internal, "internal", message, details);
         case Code::NotFound:
             return ApiError(ErrCode::NotFound, "not_found", notFoundMessage);
         case Code::PermissionDenied:
@@ -32,14 +51,19 @@ ApiError translate(Code code, const std::string& message, const std::string& not
             return ApiError(ErrCode::Unprocessable, "validation", message);
         case Code::ResourceExhausted:
             return ApiError(ErrCode::TooManyRequests, "rate_limited", message);
+        case Code::Aborted:
+            // A stale version on a conditional write. The caller must RE-READ
+            // and retry, which is a different instruction from "the database is
+            // briefly unavailable, retry as-is" - so it gets its own 409 rather
+            // than being folded into 503 as it was when it arrived as Unknown.
+            return ApiError(ErrCode::Conflict, "version_conflict", message, details);
         case Code::Unavailable:
         case Code::DeadlineExceeded:
-        case Code::Aborted:
             return ApiError(ErrCode::Unavailable, "db_unavailable", message);
-        // Unknown covers the in-band refusals that carry no code: a version
-        // conflict, read-only mode, memory pressure. The message says which,
-        // and none of them is a server fault, so 503 rather than 500 - the
-        // caller can retry a version conflict or wait out read-only mode.
+        // Unknown no longer covers the in-band refusals - since client 2.12.0
+        // each one carries its own code. What is left here is a genuinely
+        // unclassified failure, and 503 stays the honest answer: not the
+        // caller's fault, possibly transient.
         case Code::Unknown:
             return ApiError(ErrCode::Unavailable, "db_error", message);
         default:
@@ -47,15 +71,49 @@ ApiError translate(Code code, const std::string& message, const std::string& not
     }
 }
 
+/// The machine-readable half of a FailureDetail, for `error.details`.
+///
+/// Only what a caller can act on: which field collided and with what, which
+/// relation refused a delete, and the version it actually found. `reason` is
+/// deliberately NOT exported - it is how we choose the status, and a caller
+/// should branch on the slug we give it rather than on the database's wording.
+nlohmann::json detailsJson(const smartbotic::database::Client::FailureDetail& d) {
+    nlohmann::json out = nlohmann::json::object();
+    if (!d.fields.empty()) {
+        // One field reads better than a list of one, and a composite
+        // constraint is the only thing that reports several.
+        if (d.fields.size() == 1) out["field"] = d.fields.front();
+        else out["fields"] = d.fields;
+    }
+    if (d.values.is_object() && !d.values.empty()) out["values"] = d.values;
+    if (!d.conflictingId.empty()) out["conflicting_document_id"] = d.conflictingId;
+    if (!d.relation.empty()) out["relation"] = d.relation;
+    if (d.currentVersion) out["current_version"] = *d.currentVersion;
+    return out;
+}
+
 }  // namespace
 
 ApiError apiErrorFor(const smartbotic::database::Client::Failure& f,
                      const std::string& notFoundMessage) {
-    return translate(f.code, f.message, notFoundMessage);
+    // The reason-less overload: a FailedPrecondition arriving here cannot be
+    // told apart, so it lands on the honest 500 rather than a guessed 422.
+    // Callers that can should use the FailureDetail form below.
+    return translate(f.code, f.message, notFoundMessage, "", nlohmann::json::object());
+}
+
+ApiError apiErrorFor(const smartbotic::database::Client::FailureDetail& d,
+                     const std::string& notFoundMessage) {
+    return translate(d.code, d.message, notFoundMessage, d.reason, detailsJson(d));
 }
 
 ApiError apiErrorFor(const smartbotic::database::Client::Error& e) {
-    return translate(e.code(), e.what(), "no such document");
+    // A thrown failure carries its detail alongside, unless it was caught by
+    // value - which slices it off, so this must tolerate a null.
+    if (const auto* d = smartbotic::database::Client::errorDetail(e))
+        return translate(d->code, d->message.empty() ? e.what() : d->message, "no such document",
+                         d->reason, detailsJson(*d));
+    return translate(e.code(), e.what(), "no such document", "", nlohmann::json::object());
 }
 
 }  // namespace svapi

+ 9 - 0
src/db_errors.hpp

@@ -28,4 +28,13 @@ ApiError apiErrorFor(const smartbotic::database::Client::Failure& f,
 /// the find/search calls).
 ApiError apiErrorFor(const smartbotic::database::Client::Error& e);
 
+/// Build the ApiError from the FULL detail (client 2.12.0). Prefer this
+/// wherever the call offers a `FailureDetail&` overload: it is the only form
+/// that can tell a missing parent from a restricted delete from a read-only
+/// database, all three of which the database reports as FailedPrecondition. It
+/// also carries the field a duplicate collided on, which used to be recovered
+/// by parsing the error sentence.
+ApiError apiErrorFor(const smartbotic::database::Client::FailureDetail& d,
+                     const std::string& notFoundMessage = "no such document");
+
 } // namespace svapi

+ 123 - 0
src/documents_util.hpp

@@ -0,0 +1,123 @@
+#pragma once
+#include "errors.hpp"
+#include <nlohmann/json.hpp>
+#include <cerrno>
+#include <cstdint>
+#include <cstdlib>
+#include <optional>
+#include <string>
+#include <vector>
+
+/// The pure half of the document handlers: body shaping, the database's
+/// read-only metadata fields, and the `?if_version=` value.
+///
+/// Header-only and dependent on nothing but nlohmann/json and `errors.hpp`, so
+/// it can be compiled and exercised without the database client - which is what
+/// makes these rules testable at all. The handlers in `handlers/documents.cpp`
+/// link the world and cannot be instantiated in a unit test.
+namespace svapi {
+
+/// Fields the database ATTACHES to every document it hands back from get() and
+/// find(): they are not part of the stored body and cannot be written.
+///
+/// They have to be stripped from anything we send back INTO the database.
+/// Only `Client::update()` strips them itself; `insert()`, `upsert()` and
+/// `updateIfVersion()` do not, so a caller that reads a document, edits a field
+/// and writes the whole thing back would otherwise store `_version` and friends
+/// as ordinary fields - frozen at the value they had when it read, and shadowing
+/// the real metadata on every later read. The read-modify-write loop is exactly
+/// what `?if_version=` is for, so this is the loop that must not corrupt a
+/// document.
+///
+/// The names are reserved by the database (its projection layer always carries
+/// them across), so refusing to store a field of the same name costs a caller
+/// nothing: it could never read its own value back.
+inline const std::vector<std::string>& dbMetadataFields() {
+    static const std::vector<std::string> f{
+        "_id", "_version", "_created_at", "_updated_at", "_created_by", "_updated_by"};
+    return f;
+}
+
+inline void stripDbMetadata(nlohmann::json& doc) {
+    if (!doc.is_object()) return;
+    for (const auto& k : dbMetadataFields()) doc.erase(k);
+}
+
+/// The version the database reported for a document it handed back.
+///
+/// Returns nullopt rather than a default when the field is missing or not a
+/// number: a conditional write must refuse rather than compare against a made-up
+/// version, and "the database told us nothing" is not version 0.
+inline std::optional<uint64_t> documentVersion(const nlohmann::json& doc) {
+    if (!doc.is_object()) return std::nullopt;
+    auto it = doc.find("_version");
+    if (it == doc.end() || !it->is_number_integer()) return std::nullopt;
+    // Signed as well as unsigned: how a JSON number lands in either slot
+    // depends on where it was built, and a negative value is not a version.
+    if (it->is_number_integer() && !it->is_number_unsigned() && it->get<int64_t>() < 0)
+        return std::nullopt;
+    return it->get<uint64_t>();
+}
+
+/// Parse an `if_version` query value. Versions start at 1, so 0 is rejected
+/// rather than quietly meaning "any" or "must not exist" - a conditional write
+/// that silently stops being conditional is the one failure mode this parameter
+/// exists to prevent.
+inline uint64_t parseVersionValue(const std::string& raw) {
+    if (raw.empty() || raw.find_first_not_of("0123456789") != std::string::npos)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "if_version must be a positive integer");
+    errno = 0;
+    unsigned long long wide = std::strtoull(raw.c_str(), nullptr, 10);
+    // ERANGE covers a value too large for the 64-bit version counter; 0 is not
+    // a version the database ever assigns (an insert produces 1).
+    if (errno != 0 || wide == 0)
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "if_version must be a positive integer");
+    return (uint64_t)wide;
+}
+
+/// The document carried by a write request, accepting both shapes:
+///
+///   {"data": {...}}   a wrapper, unwrapped here
+///   {...}             the document itself
+///
+/// `id` is never a field: POST takes the document id from the body, PUT and
+/// PATCH from the URL, so it is removed either way. The database's own metadata
+/// fields go too - see `dbMetadataFields()`.
+///
+/// A `data` key next to any OTHER top-level key is refused. Taking body["data"]
+/// and discarding the siblings loses them silently, which is how a caller ends
+/// up missing fields with nothing in the response to say so.
+///
+/// A document whose own top-level field is named `data` is still writable by
+/// nesting it once: {"data": {"data": ...}}.
+inline nlohmann::json documentBody(const nlohmann::json& body) {
+    if (!body.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "body must be a JSON object");
+
+    if (body.contains("data")) {
+        std::vector<std::string> siblings;
+        for (auto it = body.begin(); it != body.end(); ++it)
+            if (it.key() != "data" && it.key() != "id") siblings.push_back(it.key());
+        if (!siblings.empty()) {
+            std::string list;
+            for (const auto& k : siblings) list += (list.empty() ? "" : ", ") + k;
+            throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
+                           "'data' is treated as a wrapper and must be the only top-level field, "
+                           "but found alongside: " + list +
+                           ". Send the document on its own, or nest it as {\"data\":{\"data\":...}}.");
+        }
+        nlohmann::json data = body["data"];
+        if (data.is_object() && data.contains("id")) data.erase("id");
+        stripDbMetadata(data);
+        return data;
+    }
+
+    nlohmann::json doc = body;
+    if (doc.contains("id")) doc.erase("id");
+    stripDbMetadata(doc);
+    return doc;
+}
+
+} // namespace svapi

+ 361 - 0
src/function_events.cpp

@@ -0,0 +1,361 @@
+#include "function_events.hpp"
+
+#include "db_gateway.hpp"
+#include "function_jobs.hpp"
+#include "function_record.hpp"
+#include "function_registry.hpp"
+// For skipForSingleFlight(): single flight means the same thing for an event
+// trigger as for a cron tick, so it has exactly one implementation.
+#include "function_scheduler.hpp"
+#include <spdlog/spdlog.h>
+#include <chrono>
+#include <ctime>
+#include <utility>
+
+namespace svapi {
+
+FunctionEventWatcher::FunctionEventWatcher(DbGateway& db, FunctionRegistry& registry,
+                                           FunctionJobQueue& jobs,
+                                           FunctionEventWatcherOptions opts)
+    : db_(db), registry_(registry), jobs_(jobs), opts_(opts),
+      plan_(std::make_shared<const FunctionWatchPlan>()) {
+    if (opts_.refreshIntervalSec == 0) opts_.refreshIntervalSec = 15;
+    if (opts_.maxPendingEvents == 0) opts_.maxPendingEvents = 1;
+}
+
+FunctionEventWatcher::~FunctionEventWatcher() { stop(); }
+
+std::shared_ptr<const FunctionWatchPlan> FunctionEventWatcher::plan() const {
+    std::lock_guard<std::mutex> lk(m_);
+    return plan_;
+}
+
+std::vector<std::string> FunctionEventWatcher::watched() const {
+    std::lock_guard<std::mutex> lk(m_);
+    return subscribedTo_;
+}
+
+FunctionWatchPlan FunctionEventWatcher::buildPlan() {
+    FunctionWatchPlan plan;
+    // qualify() is the ONE spelling of a project-qualified collection name.
+    // Handing it in as the qualifier keeps planAddFunction testable while
+    // guaranteeing the watched name is byte-identical to the one the rest of the
+    // service writes to - a second spelling here would mean subscribing to a
+    // collection nobody writes.
+    const CollectionQualifier qualifier = [](const std::string& project,
+                                             const std::string& collection) {
+        return qualify(project, collection);
+    };
+
+    std::vector<std::string> projects;
+    try {
+        projects = db_.listProjects();
+    } catch (const std::exception& e) {
+        // Returning an empty plan here would unsubscribe from everything on one
+        // failed call, so throw instead and let refresh() keep the old plan.
+        spdlog::warn("function event watcher could not list projects: {}", e.what());
+        throw;
+    }
+
+    for (const std::string& project : projects) {
+        std::vector<FunctionRecord> rows;
+        try {
+            rows = registry_.list(project);
+        } catch (const std::exception& e) {
+            spdlog::warn("function event watcher could not read registry for '{}': {}",
+                         project, e.what());
+            throw;
+        }
+        for (const FunctionRecord& row : rows)
+            planAddFunction(plan, qualifier, project, row.functionId, row.descriptor,
+                            row.enabled, row.valid);
+    }
+
+    planFinalise(plan);
+    return plan;
+}
+
+bool FunctionEventWatcher::refresh() {
+    FunctionWatchPlan fresh;
+    try {
+        fresh = buildPlan();
+    } catch (const std::exception&) {
+        // Already logged. Keep the previous plan and the previous stream: a
+        // transient registry read failure must not silently stop delivering
+        // events to functions that are perfectly fine.
+        return false;
+    }
+
+    auto snapshot = std::make_shared<const FunctionWatchPlan>(std::move(fresh));
+
+    bool needResubscribe = false;
+    {
+        std::lock_guard<std::mutex> lk(m_);
+        // Compare the COLLECTION SET only. Everything else about the plan - a
+        // function's event, its single-flight flag, a function added on a
+        // collection already watched - changes the targets, not the stream. This
+        // is what stops a registry poll every 15 s from tearing down and
+        // reopening a subscription forever.
+        needResubscribe = snapshot->collections != subscribedTo_;
+        plan_ = snapshot;
+        if (!needResubscribe) return false;
+    }
+
+    // Drop the old stream BEFORE opening the new one. The alternative (open,
+    // then drop) overlaps the two and delivers some events twice, which would
+    // run a side-effecting function twice; this instead leaves a short gap in
+    // which an event is missed. Given the choice the repo makes everywhere else
+    // - never run a side effect twice - a gap on a plan change is the lesser
+    // evil. It is a real gap, and worth remembering before anyone shortens
+    // refreshIntervalSec.
+    //
+    // Taken out from under m_ and released with the lock DROPPED: destroying a
+    // subscription handle can block until the client's event thread is done,
+    // and that thread may be inside onEvent waiting for m_. Destroying it while
+    // holding m_ is therefore a deadlock, not a tidiness question.
+    {
+        std::shared_ptr<void> old;
+        {
+            std::lock_guard<std::mutex> lk(m_);
+            old.swap(sub_);
+        }
+        old.reset();
+    }
+
+    std::shared_ptr<void> handle;
+    if (!snapshot->collections.empty()) {
+        try {
+            // subscribeEvents, not subscribe: the Event says WHO caused the
+            // change. That actor is the loop guard's whole basis, and reading
+            // it from the event is both exact and free - the alternative was a
+            // version-history lookup per event, which raced any later write and
+            // recorded nothing usable for a delete.
+            handle = db_.client().subscribeEvents(
+                snapshot->collections,
+                [this](const smartbotic::database::Client::Event& ev) {
+                    onEvent(ev.collection, ev.id, ev.eventType, ev.data,
+                            depthFromActor(ev.actor));
+                });
+        } catch (const std::exception& e) {
+            spdlog::warn("function event subscribe failed: {}", e.what());
+            // subscribedTo_ stays as it was, so the next refresh sees a
+            // difference and tries again rather than believing it is subscribed.
+            return false;
+        }
+    }
+
+    {
+        std::lock_guard<std::mutex> lk(m_);
+        sub_ = std::move(handle);
+        subscribedTo_ = snapshot->collections;
+    }
+    spdlog::info("function event watcher now watching {} collection(s)",
+                 snapshot->collections.size());
+    return true;
+}
+
+void FunctionEventWatcher::onEvent(const std::string& collection, const std::string& id,
+                                   const std::string& eventType,
+                                   const std::optional<nlohmann::json>& data,
+                                   uint32_t cameFromDepth) {
+    // This runs on the database client's event thread. Two absolute rules: no
+    // exception may escape (it would unwind through the client's stream loop),
+    // and no database round trip (it would stall every other subscriber in the
+    // process, SettingsStore's hot reload included). So: pure matching here,
+    // and the enqueue handed to our own thread.
+    try {
+        if (isNeverWatched(collection)) {
+            // Cannot happen through a plan built by planAddFunction. Kept
+            // unconditional anyway: this is the guard that stops the runtime
+            // triggering on its own job queue, and it costs a string compare.
+            spdlog::warn("ignoring event on reserved collection '{}'", collection);
+            return;
+        }
+
+        std::shared_ptr<const FunctionWatchPlan> p = plan();
+        const auto it = p->targets.find(collection);
+        if (it == p->targets.end()) return;
+
+        const nlohmann::json* doc = data.has_value() ? &*data : nullptr;
+
+        for (const FunctionEventTarget& t : it->second) {
+            if (!eventTriggers(t.descriptor, t.collection, collection, eventType)) continue;
+
+            PendingJob job;
+            job.project         = t.project;
+            job.functionId      = t.functionId;
+            job.singleFlight    = t.descriptor.singleFlight;
+            job.eventCollection = collection;
+            job.cameFromDepth   = cameFromDepth;
+            job.maxDepth        = opts_.maxDepth;
+            job.payload      = nlohmann::json{
+                {"collection", collection},
+                {"table", unqualifiedCollection(collection)},
+                {"id", id},
+                {"event", eventType},
+                {"document", doc != nullptr ? *doc : nlohmann::json(nullptr)}};
+
+            std::lock_guard<std::mutex> lk(qM_);
+            if (pending_.size() >= opts_.maxPendingEvents) {
+                // Drop the NEWEST rather than the oldest: the queue being full
+                // means we are already behind, and discarding work already
+                // accepted is worse than refusing new work. Counted and logged
+                // sparsely so a bulk import does not write a million lines.
+                if (++dropped_ % 100 == 1)
+                    spdlog::warn("function event buffer full ({} events); dropped {} so far",
+                                 opts_.maxPendingEvents, dropped_);
+                continue;
+            }
+            pending_.push_back(std::move(job));
+            qCv_.notify_one();
+        }
+    } catch (const std::exception& e) {
+        spdlog::warn("function event handling failed for {}/{}: {}", collection, id, e.what());
+    } catch (...) {
+        spdlog::warn("function event handling failed for {}/{}: unknown error", collection, id);
+    }
+}
+
+void FunctionEventWatcher::drain() {
+    for (;;) {
+        PendingJob job;
+        {
+            std::lock_guard<std::mutex> lk(qM_);
+            if (pending_.empty()) return;
+            job = std::move(pending_.front());
+            pending_.pop_front();
+        }
+
+        // Provenance first: a refused chain costs nothing further. The depth
+        // came from the EVENT, which states who caused the change, so there is
+        // no second read and no race with a later write.
+        const std::optional<uint32_t> depth = depthForEvent(job.cameFromDepth, job.maxDepth);
+        if (!depth) {
+            // LOUD on purpose. A refused trigger means a function is feeding
+            // itself and the chain has hit the ceiling: that is a bug somebody
+            // shipped, not a routine condition, and this line is the only place
+            // it can be noticed.
+            spdlog::error("refusing to trigger {}/{} on {}: trigger depth {} has reached the "
+                          "limit of {} - a function is very likely writing to a table it watches",
+                          job.project, job.functionId, job.eventCollection, job.cameFromDepth,
+                          job.maxDepth);
+            continue;
+        }
+
+        bool active = false;
+        if (job.singleFlight) {
+            try {
+                active = jobs_.hasActive(job.project, job.functionId);
+            } catch (const std::exception& e) {
+                active = opts_.skipWhenSingleFlightUnknown;
+                spdlog::warn("single-flight check failed for {}/{}: {}",
+                             job.project, job.functionId, e.what());
+            }
+        }
+        if (skipForSingleFlight(job.singleFlight, active)) {
+            // Note this also bounds a self-triggering chain independently of the
+            // depth guard: a single-flight function cannot have two queued
+            // copies, however many events it generates for itself.
+            spdlog::info("event trigger skipped for {}/{}: previous job still pending or "
+                         "claimed (single flight)", job.project, job.functionId);
+            continue;
+        }
+
+        FunctionJob out;
+        out.project    = job.project;
+        out.functionId = job.functionId;
+        out.trigger    = "db";
+        out.payload    = std::move(job.payload);
+        out.depth      = *depth;
+        out.runAfter   = 0;   // due immediately; an event is already late
+        out.createdAt  = static_cast<uint64_t>(std::time(nullptr));
+
+        try {
+            const std::string jobId = jobs_.enqueue(out);
+            if (jobId.empty())
+                spdlog::warn("could not enqueue event job for {}/{}", out.project,
+                             out.functionId);
+            else
+                spdlog::debug("enqueued event job {} for {}/{} at depth {}", jobId,
+                              out.project, out.functionId, out.depth);
+        } catch (const std::exception& e) {
+            spdlog::warn("could not enqueue event job for {}/{}: {}", out.project,
+                         out.functionId, e.what());
+        }
+    }
+}
+
+void FunctionEventWatcher::loop() {
+    std::time_t lastRefresh = std::time(nullptr);
+    for (;;) {
+        drain();
+
+        const std::time_t now = std::time(nullptr);
+        if (now - lastRefresh >= static_cast<std::time_t>(opts_.refreshIntervalSec)) {
+            refresh();
+            lastRefresh = now;
+        }
+
+        // Woken by an event or by the refresh deadline, whichever comes first.
+        // The wait is capped at a second so the refresh deadline is honoured
+        // even on a completely idle stream.
+        std::unique_lock<std::mutex> lk(qM_);
+        qCv_.wait_for(lk, std::chrono::seconds(1), [this] {
+            if (!pending_.empty()) return true;
+            std::lock_guard<std::mutex> l2(lifeM_);
+            return stop_;
+        });
+        {
+            std::lock_guard<std::mutex> l2(lifeM_);
+            if (stop_ && pending_.empty()) return;
+        }
+    }
+}
+
+void FunctionEventWatcher::start() {
+    {
+        std::lock_guard<std::mutex> lk(lifeM_);
+        if (started_) return;
+        started_ = true;
+        stop_ = false;
+    }
+    // Subscribe before the thread exists so a start() that fails to reach the
+    // database is visible in the log at startup rather than 15 s later.
+    refresh();
+    th_ = std::thread([this] { loop(); });
+    spdlog::info("function event watcher started (max depth {}, refresh {}s)",
+                 opts_.maxDepth, opts_.refreshIntervalSec);
+}
+
+void FunctionEventWatcher::stop() {
+    {
+        std::lock_guard<std::mutex> lk(lifeM_);
+        if (!started_) return;
+        stop_ = true;
+    }
+    // Drop the stream first: no new events can arrive while we are shutting
+    // down, so the drain the thread does on its way out is the last one.
+    // Same rule as in refresh(): swap the handle out under m_, destroy it with
+    // the lock released, because the destructor may wait on the very thread that
+    // wants m_.
+    {
+        std::shared_ptr<void> old;
+        {
+            std::lock_guard<std::mutex> lk(m_);
+            old.swap(sub_);
+            subscribedTo_.clear();
+        }
+        old.reset();
+    }
+    qCv_.notify_all();
+    if (th_.joinable()) th_.join();
+    std::lock_guard<std::mutex> lk(lifeM_);
+    started_ = false;
+}
+
+bool FunctionEventWatcher::running() const {
+    std::lock_guard<std::mutex> lk(lifeM_);
+    return started_ && !stop_;
+}
+
+} // namespace svapi

+ 380 - 0
src/function_events.hpp

@@ -0,0 +1,380 @@
+#pragma once
+
+// Database events -> function jobs.
+//
+// A `type: 'db'` function declares a table and an event (INSERT/UPDATE/DELETE).
+// This watcher collects every such table across every project, opens ONE
+// subscribe stream for the union, and turns each matching event into a queued
+// job. Like the cron scheduler, it lives in vectorapi because there must be
+// exactly one of it.
+//
+// THE THING THAT MATTERS HERE IS THE DEPTH GUARD. A function that writes to a
+// table it watches re-triggers itself, and the loop is not theoretical: it is
+// the single most likely way this feature takes a production database down. So:
+//
+//   * The job record carries `depth`, and a job is REFUSED once the chain
+//     reaches the configured maximum. The refusal is logged at error, not
+//     debug: a refused trigger means somebody shipped a loop and needs to know.
+//   * The runtime's own bookkeeping collections are NEVER watched
+//     (isNeverWatched below). Watching the job queue would make every enqueue
+//     an event, every event an enqueue - a loop with no function in it at all.
+//   * `singleFlight` applies to event triggers too, which bounds how fast a
+//     chain can grow even where provenance is unavailable.
+//
+// As in function_scheduler.hpp, every DECISION is a pure function in this
+// header and all the I/O is in the .cpp, so the decisions are testable on a
+// host where the database client cannot link.
+
+#include "functions/descriptor.hpp"
+#include <algorithm>
+#include <condition_variable>
+#include <cstdint>
+#include <deque>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <nlohmann/json.hpp>
+#include <optional>
+#include <string>
+#include <thread>
+#include <unordered_map>
+#include <vector>
+
+namespace svapi {
+
+class DbGateway;
+class FunctionRegistry;
+class FunctionJobQueue;
+
+// ---------------------------------------------------------------------------
+// Pure decisions
+// ---------------------------------------------------------------------------
+
+/// The unqualified collection name inside a possibly project-qualified one.
+/// `qualify()` joins with ':' and leaves the default project's collections
+/// bare, so a name with no ':' is already unqualified.
+///
+/// Spelled out here rather than taken from db_gateway.hpp so this header stays
+/// free of the database client. It only ever has to find the separator, which
+/// is also why collection names are forbidden from containing ':'.
+inline std::string unqualifiedCollection(const std::string& qualified) {
+    const std::string::size_type pos = qualified.find(':');
+    return pos == std::string::npos ? qualified : qualified.substr(pos + 1);
+}
+
+/// Collections the function runtime must NEVER watch.
+///
+/// Everything the runtime stores about itself lives under the reserved
+/// `vectorapi_` prefix: `vectorapi_function_jobs` (the queue),
+/// `vectorapi_functions` (the registry), `vectorapi_function_runs` (the run
+/// log), `vectorapi_keys`, `vectorapi_settings` and
+/// `vectorapi_collections`. Watching any of them means the runtime triggers on
+/// its own bookkeeping; watching the queue in particular is a self-feeding loop
+/// that needs no user function to run away.
+///
+/// The rule is the prefix, not a list of names, because collection-create
+/// already rejects both `vectorapi_` and a leading `_`, so no user collection
+/// can be caught by it - and a bookkeeping collection added later is covered
+/// without anyone remembering to update this.
+inline bool isNeverWatched(const std::string& collection) {
+    const std::string name = unqualifiedCollection(collection);
+    if (name.rfind("vectorapi_", 0) == 0) return true;
+    // Leading-underscore names are reserved too (and misroute when qualified -
+    // see the DB v2.3.1 gotcha), so nothing legitimate can be there either.
+    if (!name.empty() && name.front() == '_') return true;
+    return false;
+}
+
+/// Map the database client's event type string onto the descriptor vocabulary.
+///
+/// The client emits "insert", "update", "delete", "expire" and "invalidate".
+/// Only the first three are triggers. `expire` (a TTL eviction) and
+/// `invalidate` (a cache event) are deliberately NOT mapped to DELETE: a
+/// function declaring DELETE means "somebody deleted this", and firing it for
+/// every TTL expiry would turn a retention policy into a traffic generator.
+inline std::optional<functions::DbEvent> dbEventFromClientString(const std::string& raw) {
+    std::string s;
+    s.reserve(raw.size());
+    for (const char c : raw) s.push_back(static_cast<char>(c >= 'A' && c <= 'Z' ? c + 32 : c));
+    if (s == "insert") return functions::DbEvent::Insert;
+    if (s == "update") return functions::DbEvent::Update;
+    if (s == "delete") return functions::DbEvent::Delete;
+    return std::nullopt;
+}
+
+/// Would this event trigger this descriptor?
+///
+/// `descriptorCollection` is the descriptor's `table` already qualified for its
+/// project (`qualify(project, d.table)`); the caller does that because
+/// qualify() belongs to the database gateway and this header stays free of it.
+/// `eventCollection` is whatever the subscribe stream reported, which is always
+/// the qualified form.
+///
+/// The never-watched check is repeated here even though planning already
+/// excludes those collections: this is the predicate that lets a job be
+/// created, so it is the right place for the guard to be unconditional.
+inline bool eventTriggers(const functions::FunctionDescriptor& d,
+                          const std::string& descriptorCollection,
+                          const std::string& eventCollection,
+                          const std::string& eventType) {
+    if (d.type != functions::TriggerType::Db) return false;
+    if (descriptorCollection.empty() || descriptorCollection != eventCollection) return false;
+    if (isNeverWatched(eventCollection)) return false;
+    const std::optional<functions::DbEvent> ev = dbEventFromClientString(eventType);
+    return ev.has_value() && *ev == d.event;
+}
+
+/// Provenance of a write, as the runner records it in the audit trail.
+///
+/// The subscribe stream reports (collection, id, eventType, data) and says
+/// nothing about who wrote the row, so the loop guard needs provenance from
+/// somewhere. The runner passes an `actor` on every write it makes, which the
+/// database keeps as `updatedBy` in version history - so a write made by a
+/// function is recognisable WITHOUT adding a field to the document body. A
+/// marker inside user data would travel into every export and every client's
+/// view of the row, which is too high a price for a loop guard.
+///
+/// Shape: `fn:<project>/<functionId>:<depth>`. Anything else - an empty actor,
+/// a human, another service - is an ordinary write at depth 0, which is what
+/// almost every event is.
+constexpr const char* kFunctionActorPrefix = "fn:";
+
+/// The depth encoded in an actor string, or 0 when it is not a function write.
+///
+/// 0 for anything unparseable: a malformed actor must not be read as a
+/// shallower chain, and it must never throw - this runs where an event is being
+/// classified, not where a request can be failed.
+inline uint32_t depthFromActor(const std::string& actor) {
+    if (actor.rfind(kFunctionActorPrefix, 0) != 0) return 0;
+    const std::size_t colon = actor.rfind(':');
+    // rfind, because the project and function id sit between the prefix and the
+    // depth and may themselves contain no colon - but if they ever did, the
+    // LAST colon is still the separator.
+    if (colon == std::string::npos || colon + 1 >= actor.size()) return 0;
+    const std::string digits = actor.substr(colon + 1);
+    for (const char c : digits)
+        if (c < '0' || c > '9') return 0;
+    if (digits.size() > 4) return 1000;  // absurd; clamp rather than wrap
+    const unsigned long v = std::stoul(digits);
+    return v > 1000ul ? 1000u : static_cast<uint32_t>(v);
+}
+
+/// The depth the job produced by this event must carry, or nullopt when the
+/// chain has reached its limit and the job must be REFUSED.
+///
+/// `maxDepth` is a count of trigger generations: with the default 3, an
+/// ordinary client write produces a depth-1 job, that job's write a depth-2
+/// job, that one a depth-3 job, and the next is refused. Three covers every
+/// pipeline anyone has actually asked for (normalise -> index -> notify) while
+/// bounding a self-watching function to three extra runs per original write
+/// instead of an unbounded queue. A maxDepth of 0 disables event chaining
+/// entirely, which is a legitimate setting for a nervous operator.
+inline std::optional<uint32_t> depthForEvent(uint32_t triggeringDepth, uint32_t maxDepth) {
+    const uint64_t next = static_cast<uint64_t>(triggeringDepth) + 1u;
+    if (next > maxDepth) return std::nullopt;
+    return static_cast<uint32_t>(next);
+}
+
+// ---------------------------------------------------------------------------
+// The watch plan
+// ---------------------------------------------------------------------------
+
+/// One function waiting on one collection.
+struct FunctionEventTarget {
+    std::string project;
+    std::string functionId;
+    /// The qualified collection this target watches, so matching never has to
+    /// re-derive it.
+    std::string collection;
+    /// Kept whole rather than reduced to (event, singleFlight): eventTriggers()
+    /// takes a descriptor, so there is exactly one place that knows what a
+    /// descriptor means.
+    functions::FunctionDescriptor descriptor;
+};
+
+/// What the watcher is watching, and why. Published as an immutable snapshot
+/// (shared_ptr) and swapped atomically, the same shape SettingsStore uses.
+struct FunctionWatchPlan {
+    /// Sorted and deduplicated qualified collection names - the argument to
+    /// subscribe(). Sorted so two plans that watch the same set compare equal
+    /// whatever order the registry returned rows in, which is what keeps the
+    /// stream from being torn down on every refresh.
+    std::vector<std::string> collections;
+    /// Qualified collection -> the targets waiting on it.
+    std::unordered_map<std::string, std::vector<FunctionEventTarget>> targets;
+};
+
+/// How a project's collection name is qualified. `qualify` in production; a
+/// parameter so planning is testable without the database gateway.
+using CollectionQualifier =
+    std::function<std::string(const std::string& project, const std::string& collection)>;
+
+/// Add one registry row to a plan. Returns true when it was added.
+///
+/// Pure. This is the filter that decides what gets watched at all, so every
+/// exclusion is here and nowhere else:
+///   * disabled or invalid -> not watched. An invalid function keeps its row and
+///     its policy but must not run, and a disabled one was deliberately turned
+///     off.
+///   * not a `db` descriptor, or an unparseable one -> not watched.
+///   * a never-watched collection -> not watched, however the descriptor asked.
+inline bool planAddFunction(FunctionWatchPlan& plan, const CollectionQualifier& qualifier,
+                            const std::string& project, const std::string& functionId,
+                            const nlohmann::json& descriptorJson, bool enabled, bool valid) {
+    if (!enabled || !valid) return false;
+    const functions::ParseResult parsed = functions::parseDescriptor(descriptorJson);
+    if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Db) return false;
+
+    const std::string coll = qualifier(project, parsed.descriptor.table);
+    if (coll.empty() || isNeverWatched(coll)) return false;
+
+    FunctionEventTarget t;
+    t.project    = project;
+    t.functionId = functionId;
+    t.collection = coll;
+    t.descriptor = parsed.descriptor;
+    plan.targets[coll].push_back(std::move(t));
+    return true;
+}
+
+/// Finalise a plan built with planAddFunction: derive the sorted, deduplicated
+/// collection list from the targets, and order each collection's targets by
+/// (project, function id). Pure.
+///
+/// The ordering is not cosmetic: it is what makes two plans over the same
+/// functions compare equal regardless of the order the database returned rows
+/// in, and comparing plans is how refresh() decides whether to leave the
+/// subscribe stream alone.
+inline void planFinalise(FunctionWatchPlan& plan) {
+    plan.collections.clear();
+    plan.collections.reserve(plan.targets.size());
+    for (auto& [coll, targets] : plan.targets) {
+        plan.collections.push_back(coll);
+        std::sort(targets.begin(), targets.end(),
+                  [](const FunctionEventTarget& a, const FunctionEventTarget& b) {
+                      return a.project == b.project ? a.functionId < b.functionId
+                                                    : a.project < b.project;
+                  });
+    }
+    std::sort(plan.collections.begin(), plan.collections.end());
+    plan.collections.erase(std::unique(plan.collections.begin(), plan.collections.end()),
+                           plan.collections.end());
+}
+
+// ---------------------------------------------------------------------------
+// The watcher
+// ---------------------------------------------------------------------------
+
+struct FunctionEventWatcherOptions {
+    /// Trigger generations allowed. See depthForEvent().
+    uint32_t maxDepth = 3;
+
+    /// How often the registries are re-read to rebuild the plan.
+    ///
+    /// Polling rather than subscribing to the registry collections: those are
+    /// bookkeeping, and the rule in this file is that the runtime never watches
+    /// its own bookkeeping. 15 s is the delay between an admin enabling a `db`
+    /// function and it starting to receive events, which is a fine price for
+    /// not having a second, special-cased subscription.
+    uint32_t refreshIntervalSec = 15;
+
+    /// Matching events buffered between the client's callback thread and the
+    /// watcher's own thread. Bounded on purpose: an unbounded buffer turns a
+    /// bulk import into unbounded memory, and dropping with a loud warning is
+    /// the honest failure. Sized so a normal burst never touches it.
+    size_t maxPendingEvents = 2048;
+
+    /// What an UNKNOWN single-flight state means - that is, what to do when the
+    /// hasActive() check itself failed. True skips the trigger: losing one run
+    /// beats running a side-effecting function twice, which is the same
+    /// reasoning RunnerPool uses for a delivered-then-unanswered job.
+    bool skipWhenSingleFlightUnknown = true;
+};
+
+/// Subscribes once to the union of watched collections and enqueues a job per
+/// matching event.
+class FunctionEventWatcher {
+public:
+    FunctionEventWatcher(DbGateway& db, FunctionRegistry& registry, FunctionJobQueue& jobs,
+                         FunctionEventWatcherOptions opts = {});
+    /// Unsubscribes, stops and joins.
+    ~FunctionEventWatcher();
+
+    FunctionEventWatcher(const FunctionEventWatcher&) = delete;
+    FunctionEventWatcher& operator=(const FunctionEventWatcher&) = delete;
+
+    /// Build the first plan, subscribe, and start the refresh thread.
+    void start();
+    /// Drop the subscription, wake the thread and join. Idempotent.
+    void stop();
+    bool running() const;
+
+    /// Re-read every project's registry and swap the plan in.
+    ///
+    /// Resubscribes ONLY when the set of collections changed. A refresh that
+    /// finds the same set swaps the targets (so a changed `event` or
+    /// `singleFlight` takes effect) and leaves the stream alone - which is the
+    /// whole reason the plan separates "what to subscribe to" from "what to do
+    /// with an event". Returns true when it resubscribed.
+    bool refresh();
+
+    /// The collection set the current stream was opened with.
+    std::vector<std::string> watched() const;
+
+    /// Handle one database event. Public so the path can be driven without a
+    /// stream. Never throws.
+    /// `cameFromDepth` is the depth the event's actor reported, already
+    /// parsed - the callback thread does no I/O.
+    void onEvent(const std::string& collection, const std::string& id,
+                 const std::string& eventType, const std::optional<nlohmann::json>& data,
+                 uint32_t cameFromDepth);
+
+    const FunctionEventWatcherOptions& options() const { return opts_; }
+
+private:
+    /// What the callback thread hands to the worker: everything needed to
+    /// enqueue, already matched. The callback does pure CPU work only; the
+    /// database round trip (hasActive + enqueue) happens on our thread, because
+    /// blocking the client's event thread stalls every other subscriber in the
+    /// process - including SettingsStore's hot reload.
+    struct PendingJob {
+        std::string project;
+        std::string functionId;
+        bool        singleFlight = false;
+        nlohmann::json payload;
+        std::string eventCollection;
+        /// The depth of the write that caused this event, from the event's own
+        /// actor. Read on the callback thread, which is now free: it is a
+        /// string parse, not a database round trip.
+        uint32_t    cameFromDepth = 0;
+        uint32_t    maxDepth = 0;
+    };
+
+
+    std::shared_ptr<const FunctionWatchPlan> plan() const;
+    FunctionWatchPlan buildPlan();
+    void drain();
+    void loop();
+
+    DbGateway&                   db_;
+    FunctionRegistry&            registry_;
+    FunctionJobQueue&            jobs_;
+    FunctionEventWatcherOptions  opts_;
+
+    mutable std::mutex           m_;
+    std::shared_ptr<const FunctionWatchPlan> plan_;
+    std::vector<std::string>     subscribedTo_;
+    std::shared_ptr<void>        sub_;
+
+    std::mutex                   qM_;
+    std::condition_variable      qCv_;
+    std::deque<PendingJob>       pending_;
+    uint64_t                     dropped_ = 0;
+
+    mutable std::mutex           lifeM_;
+    bool                         stop_ = false;
+    bool                         started_ = false;
+    std::thread                  th_;
+};
+
+} // namespace svapi

+ 328 - 0
src/function_jobs.cpp

@@ -0,0 +1,328 @@
+#include "function_jobs.hpp"
+#include "apikey.hpp"
+#include <ctime>
+#include <string>
+
+namespace svapi {
+namespace {
+
+/// The row version the client injects into every document it returns.
+/// 0 when absent or not a positive integer - a caller must then not attempt a
+/// compare-and-set, because there is nothing to compare against.
+uint64_t documentVersionOf(const nlohmann::json& doc) {
+    if (!doc.is_object()) return 0;
+    const auto it = doc.find("_version");
+    if (it == doc.end() || !it->is_number_integer()) return 0;
+    const int64_t v = it->get<int64_t>();
+    return v > 0 ? static_cast<uint64_t>(v) : 0;
+}
+
+using Client = smartbotic::database::Client;
+
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+
+/// One reclaim pass touches at most this many rows. The pass is periodic, so a
+/// backlog - a runner host that died holding hundreds of jobs - drains over the
+/// following passes instead of turning one tick into hundreds of writes while
+/// nothing else gets scheduled. Same reasoning as FunctionRunLogStore's
+/// kMaxTrimPerAppend.
+constexpr uint32_t kMaxReclaimPerPass = 200;
+
+/// A project delete is rare and must be complete, so this bound is generous
+/// rather than drip-fed; it exists only so a corrupt queue cannot ask for an
+/// unbounded result set.
+constexpr uint32_t kMaxRemovePerPass = 100000;
+
+constexpr uint32_t kDefaultListLimit = 100;
+
+/// Claimable jobs, most overdue first.
+///
+/// `run_after` is the sort key, not `created_at`, for three reasons. It is the
+/// field that says when the job became eligible, so "oldest first" by it means
+/// "longest overdue first", which is the queue order an operator expects of a
+/// scheduler. It is also the field being filtered, so the server sorts and
+/// filters on one field instead of two (the DB takes a single sort key, so a
+/// second-level tiebreak on created_at is not expressible anyway). And it keeps
+/// a backed-off retry honest: complete() pushes run_after into the future, so a
+/// repeatedly failing job queues behind work enqueued since instead of
+/// returning to the head of the queue on every pass and starving it. For a job
+/// that was never delayed run_after is its enqueue time, so the common case is
+/// still plain arrival order.
+Client::QueryOptions dueCandidates(uint64_t now, uint32_t limit) {
+    Client::QueryOptions o;
+    o.filters.push_back(Client::Filter::eq("state", "pending"));
+    o.filters.push_back(Client::Filter::lte("run_after", now));
+    o.sortField = "run_after";
+    o.sortDescending = false;
+    o.limit = limit;
+    return o;
+}
+
+}  // namespace
+
+FunctionJob FunctionJob::fromJson(const nlohmann::json& j) {
+    FunctionJob job;
+    job.jobId      = j.value("job_id", "");
+    job.project    = j.value("project", "");
+    job.functionId = j.value("function_id", "");
+    job.trigger    = j.value("trigger", "");
+    // Bound to a named reference before use: a range-for or a reference into a
+    // temporary parsed subobject dangles (CLAUDE.md).
+    if (j.contains("payload") && j.at("payload").is_object()) {
+        const nlohmann::json& payload = j.at("payload");
+        job.payload = payload;
+    }
+    job.state     = j.value("state", std::string("pending"));
+    job.claimedBy = j.value("claimed_by", "");
+    job.claimedAt = j.value("claimed_at", 0ull);
+    job.attempts  = j.value("attempts", 0u);
+    job.depth     = j.value("depth", 0u);
+    job.runAfter  = j.value("run_after", 0ull);
+    job.createdAt = j.value("created_at", 0ull);
+    job.lastError = j.value("last_error", "");
+    return job;
+}
+
+nlohmann::json FunctionJob::toJson() const {
+    // `job_id`, never `id`: the client strips a top-level `id` from stored
+    // bodies, and a job with no readable identity could never be claimed
+    // (claiming needs the id to compare-and-set on) or deleted.
+    return {{"job_id", jobId},
+            {"project", project},
+            {"function_id", functionId},
+            {"trigger", trigger},
+            {"payload", payload},
+            {"state", state},
+            {"claimed_by", claimedBy},
+            {"claimed_at", claimedAt},
+            {"attempts", attempts},
+            {"depth", depth},
+            {"run_after", runAfter},
+            {"created_at", createdAt},
+            {"last_error", lastError}};
+}
+
+FunctionJobQueue::FunctionJobQueue(DbGateway& db) : db_(db) {}
+
+void FunctionJobQueue::ensure() {
+    const std::string c = coll();
+    if (!db_.client().getCollectionInfo(c).has_value())
+        db_.client().createCollection(c, 0, /*encrypted*/ false, 0, 0);
+    // Re-open the collection even when it already existed: a collection that
+    // exists on disk but has not been touched since the server restarted does
+    // not surface its rows to find() until something opens it, which is the
+    // trap CollectionRegistry::bootstrap and KeyStore::bootstrap exist for.
+    // Cheapest possible probe - one row, no filters.
+    Client::QueryOptions probe;
+    probe.limit = 1;
+    (void)db_.client().find(c, probe);
+}
+
+std::string FunctionJobQueue::enqueue(const FunctionJob& job) {
+    ensure();
+    FunctionJob j = job;
+    // The queue owns identity when the caller does not care: a scheduler tick
+    // has no natural id for its job, and an empty id would store every job on
+    // top of the last one.
+    if (j.jobId.empty()) j.jobId = generateApiKey();
+    if (j.createdAt == 0) j.createdAt = nowSec();
+    if (j.state.empty()) j.state = "pending";
+    const std::pair<std::string, bool> res = db_.client().upsert(coll(), j.toJson(), j.jobId);
+    return res.first.empty() ? std::string() : j.jobId;
+}
+
+bool FunctionJobQueue::hasActive(const std::string& project, const std::string& functionId) {
+    Client::QueryOptions o;
+    o.filters.push_back(Client::Filter::eq("project", project));
+    o.filters.push_back(Client::Filter::eq("function_id", functionId));
+    // BOTH states, in one IN: a job that is pending has not run yet and a job
+    // that is claimed is running right now, and single-flight has to refuse a
+    // second copy in either case. Counting only one of them would let the
+    // scheduler stack a second run exactly when the first is slowest.
+    o.filters.push_back(Client::Filter::in("state", nlohmann::json::array({"pending", "claimed"})));
+    o.limit = 1;
+    return !db_.client().find(coll(), o).empty();
+}
+
+std::optional<FunctionJob> FunctionJobQueue::claimNext(const std::string& runnerId,
+                                                        uint32_t maxCandidates) {
+    if (maxCandidates == 0) maxCandidates = 1;
+    const std::string c = coll();
+    const uint64_t now = nowSec();
+    const std::vector<nlohmann::json> candidates =
+        db_.client().find(c, dueCandidates(now, maxCandidates));
+    for (const auto& doc : candidates) {
+        FunctionJob job = FunctionJob::fromJson(doc);
+        if (job.jobId.empty()) continue;  // no identity, nothing to compare-and-set on
+
+        // Compare-and-set on the version the read already gave us. The find
+        // above is not a lock: between it and this write, any number of runners
+        // may be looking at the same row, and the CAS is what settles it.
+        //
+        // `_version` is injected into every row the client returns, so asking
+        // for it separately would be a third round trip for a number already
+        // in hand. A row without one cannot be claimed safely, so it is skipped
+        // rather than claimed with a guessed version.
+        const uint64_t version = documentVersionOf(doc);
+        if (version == 0) continue;
+        job.state     = "claimed";
+        job.claimedBy = runnerId;
+        job.claimedAt = now;
+        job.attempts += 1;
+        if (!db_.client().updateIfVersion(c, job.jobId, job.toJson(), version)) {
+            // Another runner won this row - it may be executing the function at
+            // this instant. Do NOT retry it: re-reading the version and writing
+            // again is how two runners end up running one side-effecting job.
+            // Move to the next candidate instead. (Same three-way reasoning as
+            // RunnerPool's retry rule: "somebody answered" means hands off.)
+            continue;
+        }
+        // The CAS moved the row on by one, and that is the version the caller
+        // must present to complete() - otherwise its completion would be
+        // refused as superseded by its own claim.
+        job.version = version + 1;
+        // Returned as stored, so the caller sees the real attempts count and
+        // can decide whether this is a last chance.
+        return job;
+    }
+    return std::nullopt;
+}
+
+bool FunctionJobQueue::complete(const FunctionJob& job, bool ok, const std::string& error,
+                                 uint32_t retryAfterSec) {
+    if (job.jobId.empty()) return false;
+    FunctionJob next = job;
+    if (ok) {
+        next.state = "done";
+        next.lastError.clear();
+    } else if (retryAfterSec > 0) {
+        next.state    = "pending";
+        next.lastError = error;
+        next.runAfter = nowSec() + retryAfterSec;
+        // Clear the claim: a pending row that still carries a claim timestamp
+        // would be picked up by reclaimStale and have its backoff cancelled.
+        next.claimedBy.clear();
+        next.claimedAt = 0;
+    } else {
+        next.state    = "failed";
+        next.lastError = error;
+    }
+    // `attempts` is deliberately left as it is, including on success: it is the
+    // history of the job, and the admin list shows "succeeded on attempt 3".
+
+    // Compare-and-set, not a blind upsert. A claim that went stale can be
+    // reclaimed and handed to another runner while the first is still working;
+    // if that first runner then completed blindly it would overwrite the new
+    // owner - marking `done` a job executing right now, or dragging it back to
+    // `pending`. Refusing a job with no version keeps that path closed rather
+    // than silently degrading to the unsafe write.
+    // No version means the job did not come from claimNext, so there is nothing
+    // to compare against. Refused rather than silently degrading to the unsafe
+    // blind write. Reporting is the caller's: a storage class that logs makes
+    // every test that drives it need a logger.
+    if (job.version == 0) return false;
+    // False here means "somebody else owns this row now", not "the database is
+    // down" - the caller logs it and must NOT retry.
+    return db_.client().updateIfVersion(coll(), job.jobId, next.toJson(), job.version);
+}
+
+uint32_t FunctionJobQueue::reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts) {
+    // 0 means "unlimited" in several places in this codebase (log retention,
+    // TTLs). It must not mean that here: an unlimited retry budget is exactly
+    // the loop this guard exists to stop, where one poisonous job takes down
+    // every runner in turn. Treat it as a budget of one.
+    if (maxAttempts == 0) maxAttempts = 1;
+
+    const std::string c = coll();
+    const uint64_t now = nowSec();
+    const uint64_t cutoff = now > timeoutSec ? now - timeoutSec : 0;
+
+    Client::QueryOptions o;
+    o.filters.push_back(Client::Filter::eq("state", "claimed"));
+    o.filters.push_back(Client::Filter::lte("claimed_at", cutoff));
+    o.sortField = "claimed_at";  // the most abandoned first, so a bounded pass does the oldest
+    o.sortDescending = false;
+    o.limit = kMaxReclaimPerPass;
+
+    uint32_t reclaimed = 0;
+    const std::vector<nlohmann::json> stale = db_.client().find(c, o);
+    for (const auto& doc : stale) {
+        FunctionJob job = FunctionJob::fromJson(doc);
+        if (job.jobId.empty()) continue;
+
+        const uint64_t version = documentVersionOf(doc);
+        if (version == 0) continue;
+        const bool exhausted = job.attempts >= maxAttempts;
+        if (exhausted) {
+            // Retire it rather than hand it to the next runner. A job that kills
+            // the process running it would otherwise kill every runner in turn,
+            // and the queue would never drain.
+            job.state = "failed";
+            job.lastError = "abandoned by runner '" + job.claimedBy + "' after " +
+                            std::to_string(job.attempts) + " attempt(s)";
+        } else {
+            job.state = "pending";
+            job.lastError = "reclaimed from runner '" + job.claimedBy +
+                            "': claim went stale";
+            job.claimedBy.clear();
+            job.claimedAt = 0;
+            job.runAfter  = now;  // due immediately; attempts is NOT rewound
+        }
+        // Compare-and-set, not a plain write: the owning runner may be
+        // finishing this job in the window between the find above and here, and
+        // its verdict has to stand. Losing the race means the job was not
+        // stale after all, so it is not counted and not touched.
+        if (!db_.client().updateIfVersion(c, job.jobId, job.toJson(), version)) continue;
+        if (!exhausted) ++reclaimed;
+    }
+    // Only rows actually returned to pending are counted: a retired job was not
+    // recovered, and reporting it as such would make a stuck queue look busy.
+    return reclaimed;
+}
+
+std::optional<FunctionJob> FunctionJobQueue::get(const std::string& jobId) {
+    if (jobId.empty()) return std::nullopt;
+    if (auto doc = db_.client().get(coll(), jobId)) {
+        FunctionJob job = FunctionJob::fromJson(*doc);
+        if (job.jobId.empty()) job.jobId = jobId;  // the body never carries `id`
+        return job;
+    }
+    return std::nullopt;
+}
+
+bool FunctionJobQueue::remove(const std::string& jobId) {
+    if (jobId.empty()) return false;
+    return db_.client().remove(coll(), jobId);
+}
+
+std::vector<FunctionJob> FunctionJobQueue::list(const std::string& project, uint32_t limit) {
+    if (limit == 0) limit = kDefaultListLimit;
+    Client::QueryOptions o;
+    o.filters.push_back(Client::Filter::eq("project", project));
+    o.sortField = "created_at";  // arrival order, not due order: this is a history view
+    o.sortDescending = false;
+    o.limit = limit;
+    std::vector<FunctionJob> out;
+    const std::vector<nlohmann::json> rows = db_.client().find(coll(), o);
+    out.reserve(rows.size());
+    for (const auto& doc : rows) out.push_back(FunctionJob::fromJson(doc));
+    return out;
+}
+
+uint32_t FunctionJobQueue::removeForProject(const std::string& project) {
+    const std::string c = coll();
+    Client::QueryOptions o;
+    o.filters.push_back(Client::Filter::eq("project", project));
+    o.limit = kMaxRemovePerPass;
+    uint32_t removed = 0;
+    const std::vector<nlohmann::json> rows = db_.client().find(c, o);
+    for (const auto& doc : rows) {
+        // By the body's `job_id`: the client strips a top-level `id`, so the
+        // document id is only readable because it is carried in the body.
+        const std::string jobId = doc.value("job_id", std::string());
+        if (!jobId.empty() && db_.client().remove(c, jobId)) ++removed;
+    }
+    return removed;
+}
+
+}  // namespace svapi

+ 143 - 0
src/function_jobs.hpp

@@ -0,0 +1,143 @@
+#pragma once
+#include "db_gateway.hpp"
+#include <nlohmann/json.hpp>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// One queued run of a function, for a trigger that is not an HTTP request.
+///
+/// HTTP dispatch is synchronous - somebody is waiting on the socket - so it
+/// never goes through this queue. Cron and database events do, for three
+/// reasons: the work must survive the runner that was going to do it dying
+/// mid-job, several runners must be able to share the load without doing the
+/// same job twice, and a burst of events must not open a connection per event.
+///
+/// ONE global collection (`vectorapi_function_jobs` in the default project)
+/// with a `project` field, not one per project: a runner claiming work has to
+/// scan a single place, and a per-project queue would make "claim the oldest
+/// due job anywhere" into N queries.
+struct FunctionJob {
+    /// `job_id`, not `id`: the database client strips a top-level `id` from
+    /// stored bodies - the same reason API keys store `key_id`.
+    std::string jobId;
+    std::string project;
+    std::string functionId;
+    /// "cron" or "db". Recorded on the run log so an operator can tell why a
+    /// function ran.
+    std::string trigger;
+    /// What the function receives as ctx: for cron, the scheduled time; for a
+    /// database event, the collection, document id, event type and the document.
+    nlohmann::json payload = nlohmann::json::object();
+
+    /// pending -> claimed -> done | failed. A claim that goes stale returns to
+    /// pending, which is how a runner dying mid-job gets retried elsewhere.
+    std::string state = "pending";
+    std::string claimedBy;      ///< runner id, for attribution and stale detection
+    uint64_t claimedAt = 0;
+    uint32_t attempts = 0;
+    /// How many triggers deep this job is. A function that writes to a table it
+    /// watches would otherwise enqueue itself forever; the watcher refuses past
+    /// a configured maximum. Carried from day one on purpose - retrofitting a
+    /// loop guard is how you get an infinite loop in production.
+    uint32_t depth = 0;
+    /// Epoch seconds before which this job must not be claimed. Used for the
+    /// scheduled time and for backing off a retry.
+    uint64_t runAfter = 0;
+    uint64_t createdAt = 0;
+    std::string lastError;
+
+    /// The row version this job was claimed at. Set by claimNext, and what
+    /// makes complete() safe.
+    ///
+    /// Without it completing is a blind upsert, and a late completion from a
+    /// runner whose claim had already gone stale and been reclaimed would
+    /// silently overwrite the runner now executing the job - marking `done`
+    /// something still running, or resurrecting it to `pending`. Claiming was
+    /// airtight and finishing was not.
+    ///
+    /// 0 means "not claimed through claimNext", and complete() refuses it.
+    uint64_t version = 0;
+
+    /// Attempts counts STARTS, not failures: claimNext increments it when it
+    /// hands the job out, so the first run sees attempts == 1. Every retry
+    /// budget is read against that, so a worker and the stale sweeper agree on
+    /// when a job has had enough tries.
+
+    static FunctionJob fromJson(const nlohmann::json& j);
+    nlohmann::json toJson() const;
+};
+
+/// The job queue. Written by vectorapi (the scheduler and the event watcher),
+/// read and claimed by runners.
+class FunctionJobQueue {
+public:
+    explicit FunctionJobQueue(DbGateway& db);
+
+    /// Create the queue collection (idempotent), and re-open it so find()
+    /// surfaces rows after a restart - the same trap CollectionRegistry::
+    /// bootstrap exists for.
+    void ensure();
+
+    /// Enqueue. Returns the job id, or empty on failure.
+    std::string enqueue(const FunctionJob& job);
+
+    /// Is a job for this function already pending or claimed?
+    ///
+    /// This is what single-flight is built on: with it true, the scheduler
+    /// skips the tick instead of stacking a second copy of a job whose last run
+    /// has not finished.
+    bool hasActive(const std::string& project, const std::string& functionId);
+
+    /// Claim the oldest due job, atomically. Returns nullopt when there is
+    /// nothing to do or when every candidate was won by another runner.
+    ///
+    /// Claiming is a compare-and-set on the job's version, so two runners
+    /// racing for the same row cannot both win - the loser simply moves to the
+    /// next candidate. The version comes from the `_version` the read already
+    /// carried, so a claim costs two round trips (find, compare-and-set) rather
+    /// than three.
+    std::optional<FunctionJob> claimNext(const std::string& runnerId, uint32_t maxCandidates = 20);
+
+    /// Mark a claimed job finished. `ok` false records lastError and, when
+    /// `retryAfterSec` is non-zero, returns it to pending for another attempt
+    /// instead of failing it outright.
+    ///
+    /// A compare-and-set on `job.version`, so it returns FALSE when the row has
+    /// moved on - which is what stops a runner whose claim went stale from
+    /// stamping its outcome over the runner that has since taken the job.
+    /// A false return means "somebody else owns this now", not "the database
+    /// is down"; the caller should log it rather than retry.
+    bool complete(const FunctionJob& job, bool ok, const std::string& error,
+                  uint32_t retryAfterSec = 0);
+
+    /// Return claims older than `timeoutSec` to pending. This is the only thing
+    /// that recovers work from a runner that died holding a job, so it has to
+    /// run periodically whether or not anything else is happening.
+    /// Returns how many were reclaimed.
+    uint32_t reclaimStale(uint32_t timeoutSec, uint32_t maxAttempts);
+
+    /// One job by id, whatever its state. The caller must check `project`
+    /// before acting on it: an id is global, so finding a row says nothing
+    /// about who may touch it.
+    std::optional<FunctionJob> get(const std::string& jobId);
+
+    /// Delete one job by id. Returns false when there was nothing to delete.
+    /// Says nothing about whether the job may be deleted - a claimed job may be
+    /// executing right now, and that is the caller's check.
+    bool remove(const std::string& jobId);
+
+    /// Oldest-first view for the admin UI, newest state included.
+    std::vector<FunctionJob> list(const std::string& project, uint32_t limit);
+
+    /// Drop every job belonging to a project, for project deletion.
+    uint32_t removeForProject(const std::string& project);
+
+private:
+    DbGateway& db_;
+    std::string coll() const { return qualify("default", "vectorapi_function_jobs"); }
+};
+
+} // namespace svapi

+ 262 - 0
src/function_scheduler.cpp

@@ -0,0 +1,262 @@
+#include "function_scheduler.hpp"
+
+#include "db_gateway.hpp"
+#include "function_jobs.hpp"
+#include "function_record.hpp"
+#include "function_registry.hpp"
+#include "functions/cron.hpp"
+#include "functions/timezone.hpp"
+#include <spdlog/spdlog.h>
+#include <chrono>
+#include <optional>
+#include <utility>
+#include <vector>
+
+namespace svapi {
+
+namespace {
+
+/// The key under which a function's last fired minute is remembered. '\x1f'
+/// (unit separator) cannot appear in a project name - the project charset is
+/// restricted because /fn/{project}/* is unauthenticated - so two different
+/// (project, function) pairs cannot collide on one key.
+std::string lastFiredKey(const std::string& project, const std::string& functionId) {
+    return project + '\x1f' + functionId;
+}
+
+} // namespace
+
+FunctionScheduler::FunctionScheduler(DbGateway& db, FunctionRegistry& registry,
+                                     FunctionJobQueue& jobs, FunctionSchedulerOptions opts)
+    : db_(db), registry_(registry), jobs_(jobs), opts_(opts) {
+    // A tick interval of a minute or more silently drops schedules, so refuse to
+    // carry a configured value that cannot work. Clamping loudly beats firing
+    // "most" minutes and leaving an operator to wonder which ones.
+    if (opts_.tickIntervalSec == 0 || opts_.tickIntervalSec >= 60) {
+        spdlog::warn("function scheduler tick interval {}s cannot see every cron minute; "
+                     "using 20s", opts_.tickIntervalSec);
+        opts_.tickIntervalSec = 20;
+    }
+}
+
+FunctionScheduler::~FunctionScheduler() { stop(); }
+
+void FunctionScheduler::start() {
+    {
+        std::lock_guard<std::mutex> lk(m_);
+        if (started_) return;
+        started_ = true;
+        stop_ = false;
+    }
+    th_ = std::thread([this] { loop(); });
+    spdlog::info("function scheduler started (tick {}s, reclaim {}s, claim timeout {}s)",
+                 opts_.tickIntervalSec, opts_.reclaimIntervalSec, opts_.claimTimeoutSec);
+}
+
+void FunctionScheduler::stop() {
+    {
+        std::lock_guard<std::mutex> lk(m_);
+        if (!started_) return;
+        stop_ = true;
+    }
+    cv_.notify_all();
+    if (th_.joinable()) th_.join();
+    std::lock_guard<std::mutex> lk(m_);
+    started_ = false;
+}
+
+bool FunctionScheduler::running() const {
+    std::lock_guard<std::mutex> lk(m_);
+    return started_ && !stop_;
+}
+
+uint32_t FunctionScheduler::reclaimOnce() {
+    std::lock_guard<std::mutex> pass(passM_);
+    try {
+        const uint32_t n = jobs_.reclaimStale(opts_.claimTimeoutSec, opts_.maxAttempts);
+        // Worth an info line: a non-zero count means a runner died holding work,
+        // which is the kind of thing an operator wants to see in the journal
+        // rather than infer from a job that ran twice.
+        if (n > 0) spdlog::info("reclaimed {} stale function job(s)", n);
+        return n;
+    } catch (const std::exception& e) {
+        spdlog::warn("function job reclaim failed: {}", e.what());
+        return 0;
+    }
+}
+
+uint32_t FunctionScheduler::tickOnce(std::time_t now) {
+    std::lock_guard<std::mutex> pass(passM_);
+    const std::time_t minute = minuteFloor(now);
+    uint32_t enqueued = 0;
+
+    std::unordered_map<std::string, std::time_t> stillPresent;
+
+    std::vector<std::string> projects;
+    try {
+        projects = db_.listProjects();
+    } catch (const std::exception& e) {
+        // No project list means no pass. Deliberately not fatal and deliberately
+        // not remembered: the next tick tries again, and because nothing was
+        // recorded in lastFired_, a minute lost to a database blip can still
+        // fire on a later tick within the same minute.
+        spdlog::warn("function scheduler could not list projects: {}", e.what());
+        return 0;
+    }
+
+    for (const std::string& project : projects) {
+        std::vector<FunctionRecord> rows;
+        try {
+            rows = registry_.list(project);
+        } catch (const std::exception& e) {
+            spdlog::warn("function scheduler could not read registry for '{}': {}",
+                         project, e.what());
+            // Keep this project's lastFired_ entries: dropping them on a
+            // transient read failure would re-fire the current minute once the
+            // read recovers.
+            for (const auto& [key, when] : lastFired_)
+                if (key.rfind(project + '\x1f', 0) == 0) stillPresent[key] = when;
+            continue;
+        }
+
+        for (const FunctionRecord& row : rows) {
+            // A disabled or invalid function does not run. Its lastFired_ entry
+            // is dropped with it, so re-enabling starts from "has not fired",
+            // which is the same thing a restart does.
+            if (!row.enabled || !row.valid) continue;
+
+            const functions::ParseResult parsed = functions::parseDescriptor(row.descriptor);
+            if (!parsed.ok || parsed.descriptor.type != functions::TriggerType::Cron) continue;
+
+            std::string cronError;
+            const std::optional<functions::CronExpr> expr =
+                functions::CronExpr::parse(parsed.descriptor.schedule, &cronError);
+            if (!expr) {
+                // The write path validates the schedule with this same parser,
+                // so reaching here means a row was written by an older or
+                // broken path. Say so once per tick rather than silently never
+                // firing, which is indistinguishable from a broken scheduler.
+                spdlog::warn("cron function {}/{} has an unusable schedule '{}': {}",
+                             project, row.functionId, parsed.descriptor.schedule, cronError);
+                continue;
+            }
+
+            const std::string key = lastFiredKey(project, row.functionId);
+            const auto it = lastFired_.find(key);
+            const std::time_t last = it == lastFired_.end() ? 0 : it->second;
+            stillPresent[key] = last;
+
+            // The descriptor's `tz`, empty for a schedule that did not declare
+            // one. It has to reach the matcher: evaluated in UTC instead, an
+            // 08:00 Budapest schedule fires at 09:00 local in winter and 10:00
+            // in summer, and a schedule that drifts by an hour twice a year is
+            // not something anybody notices quickly.
+            const std::string& zone = parsed.descriptor.timezone;
+            if (!zone.empty() && !functions::timezoneKnown(zone)) {
+                // The write path validates `tz` against the same host tz
+                // database, so reaching here means the row predates that check
+                // or tzdata went away under us. Never firing is the safe
+                // answer - a silent UTC fallback would move the author's 08:00
+                // report - but it must be said out loud, because "never fires"
+                // and "broken scheduler" look identical from outside.
+                spdlog::warn("cron function {}/{} declares time zone '{}', which this host "
+                             "does not know; it will not fire until tzdata provides it",
+                             project, row.functionId, zone);
+                continue;
+            }
+
+            const functions::CronExpr e = *expr;
+            if (!cronDue([&e, &zone](std::time_t t) { return e.matchesIn(t, zone); }, now, last))
+                continue;
+
+            bool active = false;
+            try {
+                active = jobs_.hasActive(project, row.functionId);
+            } catch (const std::exception& ex) {
+                // Unknown whether a job is active. Treat it as active: skipping
+                // a tick loses one run, queueing a second copy of a job that is
+                // already running breaks the guarantee the author asked for.
+                spdlog::warn("single-flight check failed for {}/{}, skipping this tick: {}",
+                             project, row.functionId, ex.what());
+                active = true;
+            }
+
+            if (skipForSingleFlight(parsed.descriptor.singleFlight, active)) {
+                spdlog::info("cron tick skipped for {}/{}: previous job still pending or "
+                             "claimed (single flight)", project, row.functionId);
+                // The minute is consumed even though nothing was queued, so the
+                // next two ticks inside this minute do not re-log the same skip.
+                stillPresent[key] = minute;
+                continue;
+            }
+
+            FunctionJob job;
+            // jobId is left empty: the queue assigns it and enqueue() returns it.
+            job.project    = project;
+            job.functionId = row.functionId;
+            job.trigger    = "cron";
+            job.payload    = nlohmann::json{{"schedule", parsed.descriptor.schedule},
+                                            {"scheduled_at", static_cast<int64_t>(minute)}};
+            // A cron run starts a trigger chain rather than continuing one, so it
+            // is always depth 0. If it writes to a watched table, the event
+            // watcher is what counts from here.
+            job.depth     = 0;
+            job.runAfter  = static_cast<uint64_t>(minute);
+            job.createdAt = static_cast<uint64_t>(now);
+
+            std::string jobId;
+            try {
+                jobId = jobs_.enqueue(job);
+            } catch (const std::exception& ex) {
+                spdlog::warn("could not enqueue cron job for {}/{}: {}",
+                             project, row.functionId, ex.what());
+            }
+            if (jobId.empty()) {
+                // Not recorded as fired, so a later tick in the same minute can
+                // still get this run out. Losing a run to a database blip when a
+                // retry was available would be our bug, not the database's.
+                spdlog::warn("cron job for {}/{} was not enqueued; will retry this minute",
+                             project, row.functionId);
+                continue;
+            }
+
+            stillPresent[key] = minute;
+            ++enqueued;
+            spdlog::debug("enqueued cron job {} for {}/{}", jobId, project, row.functionId);
+        }
+    }
+
+    // Prune: a function that no longer exists, or is no longer an enabled valid
+    // cron function, must not keep an entry forever. The map is rebuilt from
+    // what this pass actually saw.
+    lastFired_ = std::move(stillPresent);
+    return enqueued;
+}
+
+void FunctionScheduler::loop() {
+    std::time_t lastReclaim = 0;
+    for (;;) {
+        const std::time_t now = std::time(nullptr);
+
+        try {
+            tickOnce(now);
+        } catch (const std::exception& e) {
+            // The loop must outlive any single bad pass: a scheduler that dies
+            // on one exception stops every schedule on the host, and nothing
+            // restarts it short of a service restart.
+            spdlog::warn("function scheduler tick failed: {}", e.what());
+        }
+
+        if (lastReclaim == 0 ||
+            now - lastReclaim >= static_cast<std::time_t>(opts_.reclaimIntervalSec)) {
+            reclaimOnce();
+            lastReclaim = now;
+        }
+
+        std::unique_lock<std::mutex> lk(m_);
+        cv_.wait_for(lk, std::chrono::seconds(opts_.tickIntervalSec), [this] { return stop_; });
+        if (stop_) return;
+    }
+}
+
+} // namespace svapi

+ 180 - 0
src/function_scheduler.hpp

@@ -0,0 +1,180 @@
+#pragma once
+
+// The cron scheduler for the function runtime.
+//
+// WHY it lives in vectorapi and not in the runner: there must be EXACTLY ONE
+// scheduler. N runners each walking the cron functions means N copies of every
+// job on every tick - the obvious bug the design document calls out by name
+// (docs/superpowers/specs/2026-10-06-function-runtime-design.md, "Runner
+// protocol"). vectorapi is already the singleton and already owns the subscribe
+// streams, so the schedule decision is made here and the work is handed to the
+// runners through FunctionJobQueue.
+//
+// Everything that DECIDES is a pure function in this header. The thread and the
+// database calls are in the .cpp. That split is deliberate: the decisions are
+// the part that can be wrong in a way nobody notices (a cron that fires twice a
+// minute, or never), and they stay testable on a host where the database client
+// cannot even link (CLAUDE.md, "The Void dev host can no longer build the C++
+// natively").
+
+#include "functions/descriptor.hpp"
+#include <condition_variable>
+#include <cstdint>
+#include <ctime>
+#include <functional>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <unordered_map>
+
+namespace svapi {
+
+// Forward declarations only. This header must stay free of the database client
+// so the pure decisions below can be compiled - and therefore tested - without
+// it.
+class DbGateway;
+class FunctionRegistry;
+class FunctionJobQueue;
+
+// ---------------------------------------------------------------------------
+// Pure decisions
+// ---------------------------------------------------------------------------
+
+/// Epoch seconds floored to the start of their minute. Cron has minute
+/// resolution, so the minute - not the second - is the unit of "has this
+/// already fired".
+inline std::time_t minuteFloor(std::time_t t) {
+    // Integer division truncates toward zero, so a negative timestamp would
+    // round the wrong way. Nothing schedules before 1970; clamp rather than be
+    // subtly wrong at the boundary.
+    if (t <= 0) return 0;
+    return t - (t % 60);
+}
+
+/// Is a cron function due at `now`, given the minute it last fired for?
+///
+/// `matchesMinute` is `functions::CronExpr::matchesIn(t, descriptor.timezone)`
+/// in production - the descriptor's `tz`, so a schedule is evaluated against
+/// wall clock in the zone its author named. It is a callable parameter rather
+/// than a CronExpr so the decision that creates jobs can be tested without the
+/// cron engine, without a database and without a thread, and so the zone is
+/// bound once at the call site instead of being threaded through every
+/// decision below.
+///
+/// `lastFiredMinute` is 0 for a function that has not fired in this process.
+/// That is also the state after a restart, and it is why MISSED TICKS ARE
+/// SKIPPED, never replayed: this function only ever asks about the minute
+/// containing `now`, so a server that was down from 02:00 to 05:00 fires at the
+/// next matching minute once and never discovers three hours of backlog. A
+/// replay would be far worse than a gap - an hourly report function would send
+/// three hours of reports in one burst, and nobody asked for that.
+///
+/// A minute at or before the last fired minute is never due, which also makes a
+/// clock stepped backwards (an NTP correction) harmless: it cannot re-fire a
+/// minute that already fired.
+inline bool cronDue(const std::function<bool(std::time_t)>& matchesMinute,
+                    std::time_t now, std::time_t lastFiredMinute) {
+    const std::time_t minute = minuteFloor(now);
+    if (lastFiredMinute != 0 && minute <= lastFiredMinute) return false;
+    return matchesMinute(now);
+}
+
+/// Must this tick be SKIPPED because the last run has not finished?
+///
+/// `singleFlight` already defaults to true for cron descriptors
+/// (functions/descriptor.cpp): a schedule firing again while the previous run
+/// is still going is almost never what the author meant, and a job that takes
+/// longer than its period would otherwise stack copies of itself until the
+/// queue is nothing but that one function. Skip and log; do not queue.
+inline bool skipForSingleFlight(bool singleFlight, bool hasActiveJob) {
+    return singleFlight && hasActiveJob;
+}
+
+// ---------------------------------------------------------------------------
+// The scheduler
+// ---------------------------------------------------------------------------
+
+struct FunctionSchedulerOptions {
+    /// How often the scheduler walks the registries.
+    ///
+    /// It MUST be strictly less than 60, or whole cron minutes are missed: the
+    /// scheduler only ever asks "does this fire in the minute containing now",
+    /// so a minute no tick lands in never fires. 20 gives three looks at every
+    /// minute, so one slow tick (a registry read against a sluggish database)
+    /// still leaves two chances, and it bounds how late a job is enqueued to
+    /// ~20 s, well inside what a minute-resolution schedule promises.
+    uint32_t tickIntervalSec = 20;
+
+    /// How often stale claims are returned to pending. On its own cadence on
+    /// purpose: reclaimStale() is the ONLY thing that recovers a job from a
+    /// runner that died holding it, so it has to run whether or not any cron is
+    /// due, and it must not be coupled to whether the registry walk found work.
+    uint32_t reclaimIntervalSec = 60;
+
+    /// A claim older than this is assumed dead. It must comfortably exceed the
+    /// longest function wall time plus a runner's claim-to-start latency, or a
+    /// slow but perfectly healthy run gets reclaimed and executed twice.
+    uint32_t claimTimeoutSec = 300;
+
+    /// Attempts after which a reclaimed job is failed instead of re-queued.
+    uint32_t maxAttempts = 3;
+};
+
+/// Walks every project's enabled and valid cron functions on a timer and
+/// enqueues the ones whose minute has arrived.
+class FunctionScheduler {
+public:
+    FunctionScheduler(DbGateway& db, FunctionRegistry& registry, FunctionJobQueue& jobs,
+                      FunctionSchedulerOptions opts = {});
+    /// Stops and joins. No detached thread, and nothing in flight when this
+    /// returns.
+    ~FunctionScheduler();
+
+    FunctionScheduler(const FunctionScheduler&) = delete;
+    FunctionScheduler& operator=(const FunctionScheduler&) = delete;
+
+    /// Start the background thread. A second call while running is a no-op.
+    void start();
+    /// Signal, wake and join. Idempotent, and safe to call without start().
+    void stop();
+    bool running() const;
+
+    /// One scheduling pass. Returns how many jobs were enqueued.
+    ///
+    /// Public and synchronous so a pass can be driven without the thread.
+    /// Serialised against the loop internally, so calling it on a running
+    /// scheduler is safe; it only costs an extra pass.
+    uint32_t tickOnce(std::time_t now);
+
+    /// One reclaim pass. Returns how many claims were returned to pending.
+    uint32_t reclaimOnce();
+
+    const FunctionSchedulerOptions& options() const { return opts_; }
+
+private:
+    void loop();
+
+    DbGateway&                 db_;
+    FunctionRegistry&          registry_;
+    FunctionJobQueue&          jobs_;
+    FunctionSchedulerOptions   opts_;
+
+    /// Guards lastFired_ and the database calls a pass makes, so an external
+    /// tickOnce() cannot interleave with the loop's.
+    std::mutex                 passM_;
+    /// project + '\x1f' + functionId -> the minute a job was last enqueued for.
+    ///
+    /// In memory on purpose. Persisting it would mean deciding what to do with a
+    /// stale entry on startup, and the only safe answer is "ignore it", which is
+    /// exactly what an empty map already does. Pruned every pass down to the
+    /// functions that still exist, so a deleted function cannot leak an entry.
+    std::unordered_map<std::string, std::time_t> lastFired_;
+
+    mutable std::mutex         m_;
+    std::condition_variable    cv_;
+    bool                       stop_ = false;
+    bool                       started_ = false;
+    std::thread                th_;
+};
+
+} // namespace svapi

+ 441 - 0
src/functions/cron.cpp

@@ -0,0 +1,441 @@
+#include "functions/cron.hpp"
+
+#include "functions/timezone.hpp"
+
+#include <algorithm>
+#include <cctype>
+#include <chrono>
+#include <vector>
+
+namespace svapi::functions {
+namespace {
+
+struct FieldSpec {
+    const char* name;
+    int min;
+    int max;
+    /// Three-letter aliases, lowest value first ("jan" = 1, "sun" = 0), or null
+    /// for the numeric-only fields.
+    const char* const* names;
+    int namesBase;
+};
+
+const char* const kMonthNames[] = {"jan", "feb", "mar", "apr", "may", "jun",
+                                   "jul", "aug", "sep", "oct", "nov", "dec", nullptr};
+const char* const kDowNames[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat", nullptr};
+
+const FieldSpec kFields[5] = {
+    {"minute", 0, 59, nullptr, 0},
+    {"hour", 0, 23, nullptr, 0},
+    {"day-of-month", 1, 31, nullptr, 0},
+    {"month", 1, 12, kMonthNames, 1},
+    // 7 is Sunday as well, which every cron implementation accepts; it folds
+    // onto 0 when the bitset is built.
+    {"day-of-week", 0, 7, kDowNames, 0},
+};
+
+/// Resolve one endpoint of a cron range: digits, or a three-letter alias where
+/// the field has them. Returns false when it is neither, or out of range.
+bool fieldValue(const std::string& tok, const FieldSpec& f, int& out) {
+    if (tok.empty()) return false;
+    const bool numeric = std::all_of(tok.begin(), tok.end(),
+                                     [](unsigned char c) { return std::isdigit(c) != 0; });
+    if (numeric) {
+        // Length-capped rather than caught: parsing user data must not depend
+        // on an exception path, and no field value needs more than two digits
+        // once leading zeros are allowed for.
+        const std::size_t firstSignificant = tok.find_first_not_of('0');
+        const std::string digits =
+            firstSignificant == std::string::npos ? "0" : tok.substr(firstSignificant);
+        if (digits.size() > 2) return false;
+        out = std::stoi(digits);
+    } else if (f.names != nullptr) {
+        std::string low = tok;
+        for (char& c : low) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+        out = -1;
+        for (int i = 0; f.names[i] != nullptr; ++i) {
+            if (low == f.names[i]) {
+                out = f.namesBase + i;
+                break;
+            }
+        }
+        if (out < 0) return false;
+    } else {
+        return false;
+    }
+    return out >= f.min && out <= f.max;
+}
+
+/// Parse one comma list - "*", "5", "1-5", "*/2", "1-5/2", "0,30" - into
+/// `out`, which is indexed by the raw field value and sized f.max + 1. Returns
+/// false for anything malformed; `out` is then meaningless, not partial, since
+/// the caller discards the whole expression.
+bool parseField(const std::string& field, const FieldSpec& f, std::vector<bool>& out) {
+    out.assign(static_cast<std::size_t>(f.max) + 1, false);
+    if (field.empty()) return false;
+
+    std::size_t pos = 0;
+    while (pos <= field.size()) {
+        const std::size_t comma = field.find(',', pos);
+        const std::string item =
+            field.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
+        if (item.empty()) return false;
+
+        std::string base = item;
+        int step = 1;
+        const std::size_t slash = item.find('/');
+        if (slash != std::string::npos) {
+            base = item.substr(0, slash);
+            const std::string stepTok = item.substr(slash + 1);
+            if (stepTok.empty() || stepTok.find('/') != std::string::npos) return false;
+            if (!std::all_of(stepTok.begin(), stepTok.end(),
+                             [](unsigned char c) { return std::isdigit(c) != 0; }))
+                return false;
+            // Length-capped before converting: parsing must never throw, and no
+            // real step needs more than two digits.
+            if (stepTok.size() > 2) return false;
+            step = std::stoi(stepTok);
+            if (step < 1) return false; // "*/0" would never fire
+        }
+
+        int lo = 0;
+        int hi = 0;
+        if (base == "*") {
+            lo = f.min;
+            hi = f.max;
+        } else {
+            const std::size_t dash = base.find('-', 1); // 1: no negative endpoints
+            if (dash == std::string::npos) {
+                if (!fieldValue(base, f, lo)) return false;
+                // "5/10" is a start value, not a lone one: Vixie cron reads it
+                // as 5 and every tenth value up to the field maximum, and the
+                // parser this replaced accepted the syntax, so it must mean
+                // something rather than quietly collapsing to "5".
+                hi = slash == std::string::npos ? lo : f.max;
+            } else {
+                if (!fieldValue(base.substr(0, dash), f, lo)) return false;
+                if (!fieldValue(base.substr(dash + 1), f, hi)) return false;
+                if (lo > hi) return false;
+            }
+        }
+        for (int v = lo; v <= hi; v += step) out[static_cast<std::size_t>(v)] = true;
+
+        if (comma == std::string::npos) break;
+        pos = comma + 1;
+        if (pos == field.size()) return false; // trailing comma
+    }
+    return true;
+}
+
+std::vector<std::string> splitFields(const std::string& expr) {
+    std::vector<std::string> fields;
+    std::string cur;
+    for (const char c : expr) {
+        if (std::isspace(static_cast<unsigned char>(c)) != 0) {
+            if (!cur.empty()) fields.push_back(cur);
+            cur.clear();
+        } else {
+            cur.push_back(c);
+        }
+    }
+    if (!cur.empty()) fields.push_back(cur);
+    return fields;
+}
+
+void report(std::string* error, std::string message) {
+    if (error != nullptr) *error = std::move(message);
+}
+
+/// Decompose to UTC calendar parts. gmtime_r, never localtime_r: a schedule
+/// must mean the same thing on every host the service is moved to.
+std::tm utcParts(std::time_t t) {
+    std::tm tm{};
+    gmtime_r(&t, &tm);
+    return tm;
+}
+
+constexpr std::time_t kMinute = 60;
+constexpr std::time_t kDay = 24 * 60 * 60;
+
+/// Round down to the start of the minute containing `t`. Written as a floor and
+/// not as `t / 60 * 60` because integer division truncates towards zero, which
+/// is the wrong direction for a pre-1970 timestamp.
+std::time_t floorMinute(std::time_t t) {
+    const std::time_t rem = t % kMinute;
+    return rem >= 0 ? t - rem : t - rem - kMinute;
+}
+
+// ---------------------------------------------------------------------------
+// Wall-clock arithmetic, for the zone-aware paths
+// ---------------------------------------------------------------------------
+//
+// A zone-aware search walks a zone's WALL CLOCK, not UTC, and that is the whole
+// trick: a wall-clock minute that DST skipped is still a candidate here, which
+// is how it can fire at the end of the gap instead of being lost. Walking UTC
+// instead would never produce it, because it never happened.
+//
+// The arithmetic below therefore has no zone in it at all. A zone is consulted
+// in exactly one place - utcFromLocal(), where a wall clock becomes an instant
+// - so there is one answer to every DST question and it lives in timezone.cpp.
+
+constexpr long long kMinutesPerDay = 24 * 60;
+
+/// A wall-clock minute, decomposed.
+struct Civil {
+    int year = 0;
+    int month = 0;
+    int day = 0;
+    int hour = 0;
+    int minute = 0;
+    int weekday = 0;  ///< 0 = Sunday, matching cron
+};
+
+/// Wall-clock minutes since 1970-01-01 00:00 local. A plain count, so advancing
+/// by a minute, an hour or a day is arithmetic rather than calendar logic, and
+/// only the decomposition has to know about months.
+long long civilToMinutes(int year, int month, int day, int hour, int minute) {
+    const std::chrono::sys_days d{std::chrono::year{year} /
+                                  std::chrono::month{static_cast<unsigned>(month)} /
+                                  std::chrono::day{static_cast<unsigned>(day)}};
+    return static_cast<long long>(d.time_since_epoch().count()) * kMinutesPerDay + hour * 60 +
+           minute;
+}
+
+/// Floor division, because the walk must not change direction before 1970.
+/// Nothing schedules there, but a helper that is wrong for negative input is a
+/// trap for whoever reuses it next.
+long long floorDiv(long long a, long long b) {
+    const long long q = a / b;
+    return (a % b != 0 && ((a < 0) != (b < 0))) ? q - 1 : q;
+}
+
+Civil civilFromMinutes(long long m) {
+    const long long dayCount = floorDiv(m, kMinutesPerDay);
+    const long long inDay = m - dayCount * kMinutesPerDay;
+    const std::chrono::sys_days d{std::chrono::days{dayCount}};
+    const std::chrono::year_month_day ymd{d};
+    Civil c;
+    c.year = static_cast<int>(ymd.year());
+    c.month = static_cast<int>(static_cast<unsigned>(ymd.month()));
+    c.day = static_cast<int>(static_cast<unsigned>(ymd.day()));
+    c.hour = static_cast<int>(inDay / 60);
+    c.minute = static_cast<int>(inDay % 60);
+    c.weekday = static_cast<int>(std::chrono::weekday{d}.c_encoding());
+    return c;
+}
+
+long long startOfCivilDay(long long m) { return floorDiv(m, kMinutesPerDay) * kMinutesPerDay; }
+long long startOfCivilHour(long long m) { return floorDiv(m, 60) * 60; }
+
+} // namespace
+
+std::optional<CronExpr> CronExpr::parse(const std::string& expr, std::string* error) {
+    // The message text is kept verbatim from the shape-only parser this
+    // replaced, so an author who has seen one of these errors before still
+    // recognises it and the API's documented wording does not shift.
+    const std::vector<std::string> fields = splitFields(expr);
+    if (fields.size() != 5) {
+        report(error,
+               "cron 'schedule' must have exactly 5 fields (minute hour day-of-month month "
+               "day-of-week), got " +
+                   std::to_string(fields.size()));
+        return std::nullopt;
+    }
+
+    CronExpr c;
+    std::vector<bool> bits;
+    for (std::size_t i = 0; i < 5; ++i) {
+        const FieldSpec& f = kFields[i];
+        if (!parseField(fields[i], f, bits)) {
+            report(error, std::string("cron 'schedule' field ") + std::to_string(i + 1) + " (" +
+                              f.name + ") is not valid: '" + fields[i] + "'");
+            return std::nullopt;
+        }
+        for (std::size_t v = 0; v < bits.size(); ++v) {
+            if (!bits[v]) continue;
+            switch (i) {
+            case 0: c.minute_[v] = true; break;
+            case 1: c.hour_[v] = true; break;
+            case 2: c.dom_[v] = true; break;
+            case 3: c.month_[v] = true; break;
+            // Both 0 and 7 are Sunday, so the two fold onto one bit here and
+            // "5-7" keeps meaning Friday through Sunday.
+            default: c.dow_[v % 7] = true; break;
+            }
+        }
+    }
+
+    // "Restricted" is decided by the text, not by the resulting bitset: a field
+    // beginning with '*' is a star for the OR rule even when it carries a step,
+    // which is how Vixie cron reads it and therefore what a copied crontab line
+    // means. Deciding it from the bits instead would make "1-31/1" behave
+    // differently from "*/1" despite selecting the same days.
+    c.domRestricted_ = fields[2].front() != '*';
+    c.dowRestricted_ = fields[4].front() != '*';
+    report(error, {});
+    return c;
+}
+
+bool CronExpr::dayMatches(int dayOfMonth, int dayOfWeek) const {
+    const bool domOk = dom_[dayOfMonth];
+    const bool dowOk = dow_[dayOfWeek];
+    // The rule everyone gets wrong: with both day fields restricted the two are
+    // OR'd, so "0 0 13 * FRI" is the 13th or any Friday - not Friday the 13th.
+    if (domRestricted_ && dowRestricted_) return domOk || dowOk;
+    return domOk && dowOk;
+}
+
+bool CronExpr::fieldsMatch(int month, int dayOfMonth, int dayOfWeek, int hour,
+                           int minute) const {
+    if (!minute_[minute] || !hour_[hour]) return false;
+    if (!month_[month]) return false;
+    return dayMatches(dayOfMonth, dayOfWeek);
+}
+
+bool CronExpr::matches(std::time_t t) const {
+    const std::tm tm = utcParts(t);
+    // tm_sec is deliberately never read: this is a minute-resolution schedule,
+    // so a tick at :00 and a tick at :59 of the same minute must agree.
+    return fieldsMatch(tm.tm_mon + 1, tm.tm_mday, tm.tm_wday, tm.tm_hour, tm.tm_min);
+}
+
+std::optional<std::time_t> CronExpr::nextFire(std::time_t after) const {
+    std::time_t t = floorMinute(after) + kMinute; // strictly after, minute aligned
+
+    // One year and a day of search. The bound is what makes a legal but
+    // impossible expression - "0 0 30 2 *" is Feb 30 - answer "never" instead
+    // of spinning; the extra day covers a leap year's worth of days so a
+    // schedule that does fire once a year is still found.
+    const std::time_t limit = t + 366 * kDay;
+
+    while (t <= limit) {
+        const std::tm tm = utcParts(t);
+        if (!month_[tm.tm_mon + 1] || !dayMatches(tm.tm_mday, tm.tm_wday)) {
+            // Skip the rest of the day in one step rather than a minute at a
+            // time: an expression like "0 0 29 2 *" would otherwise walk half a
+            // million minutes to reach its answer.
+            t += kDay - (tm.tm_hour * 3600 + tm.tm_min * 60 + tm.tm_sec);
+            continue;
+        }
+        if (!hour_[tm.tm_hour]) {
+            t += 3600 - (tm.tm_min * 60 + tm.tm_sec);
+            continue;
+        }
+        if (!minute_[tm.tm_min]) {
+            t += kMinute;
+            continue;
+        }
+        return t;
+    }
+    return std::nullopt;
+}
+
+bool CronExpr::matchesIn(std::time_t t, const std::string& zone) const {
+    // Empty zone is the old path verbatim, not a reimplementation of it: a
+    // schedule that carries no `tz` cannot change meaning because this overload
+    // exists.
+    if (zone.empty()) return matches(t);
+
+    const std::time_t tm = floorMinute(t);
+    const std::optional<ZoneParts> here = zonePartsAt(zone, tm);
+    // An unknown zone - or a host with no tz database - never fires. The write
+    // path refuses an unknown zone, so a row that has one predates that check,
+    // and a silent UTC fallback would move the author's 08:00 by an hour and
+    // look like it had worked.
+    if (!here) return false;
+
+    if (fieldsMatch(here->month, here->day, here->weekday, here->hour, here->minute)) {
+        const std::optional<LocalInstant> li =
+            utcFromLocal(zone, here->year, here->month, here->day, here->hour, here->minute, 0);
+        // The equality is what makes a REPEATED wall clock fire once. When the
+        // clocks go back, 02:30 happens twice; utcFromLocal answers with the
+        // first occurrence, so the second one fails this test and the daily job
+        // does not run again an hour later.
+        if (li && li->utc == tm) return true;
+    }
+
+    // The other DST case. A SKIPPED wall-clock minute matches at the instant
+    // the gap ends, so this minute also has to answer for the minutes the
+    // clocks jumped over to arrive here. Without this, a 02:30 schedule would
+    // silently miss one night a year.
+    const std::optional<ZoneParts> before = zonePartsAt(zone, tm - kMinute);
+    if (!before) return false;
+    if (here->offsetSec <= before->offsetSec) return false;
+
+    const long long gapSec = here->offsetSec - before->offsetSec;
+    const long long nowMinutes =
+        civilToMinutes(here->year, here->month, here->day, here->hour, here->minute);
+    // The skipped wall clock runs from local(tm) - gap up to local(tm),
+    // exclusive. Walked newest first; the order is irrelevant to the answer,
+    // and the longest real gap is two hours, so this is 120 iterations at worst
+    // and only on a transition minute.
+    for (long long back = kMinute; back <= gapSec; back += kMinute) {
+        const Civil c = civilFromMinutes(nowMinutes - back / kMinute);
+        if (!fieldsMatch(c.month, c.day, c.weekday, c.hour, c.minute)) continue;
+        const std::optional<LocalInstant> li =
+            utcFromLocal(zone, c.year, c.month, c.day, c.hour, c.minute, 0);
+        // `existed` false confirms the minute really was skipped rather than
+        // merely earlier, and the equality confirms it was skipped by THIS
+        // transition and not an older one.
+        if (li && !li->existed && li->utc == tm) return true;
+    }
+    return false;
+}
+
+std::optional<std::time_t> CronExpr::nextFireIn(std::time_t after,
+                                                const std::string& zone) const {
+    if (zone.empty()) return nextFire(after);
+
+    const std::time_t start = floorMinute(after);
+    const std::optional<ZoneParts> here = zonePartsAt(zone, start);
+    if (!here) return std::nullopt;
+
+    // Walk WALL CLOCK, not UTC. A minute DST skipped is still a candidate here
+    // and utcFromLocal maps it to the end of the gap, which is exactly the
+    // behaviour this function has to produce; a UTC walk could never offer it,
+    // because that minute never happened.
+    long long m = civilToMinutes(here->year, here->month, here->day, here->hour, here->minute);
+    // A year and a day of local days. Same bound and same reason as the UTC
+    // walk: "0 0 30 2 *" is Feb 30, and it must answer "never" rather than
+    // spin. The extra day covers a leap year.
+    const long long limit = startOfCivilDay(m) + 367 * kMinutesPerDay;
+
+    while (m <= limit) {
+        const Civil c = civilFromMinutes(m);
+        // Only real dates are produced, so a day field selecting the 31st
+        // simply never matches in a 30-day month - no Feb 30 to reject.
+        if (!month_[c.month] || !dayMatches(c.day, c.weekday)) {
+            m = startOfCivilDay(m) + kMinutesPerDay;
+            continue;
+        }
+        if (!hour_[c.hour]) {
+            m = startOfCivilHour(m) + 60;
+            continue;
+        }
+        if (!minute_[c.minute]) {
+            ++m;
+            continue;
+        }
+
+        const std::optional<LocalInstant> li =
+            utcFromLocal(zone, c.year, c.month, c.day, c.hour, c.minute, 0);
+        // Strictly after the minute containing `after`, matching nextFire().
+        // A candidate whose instant is NOT after it is skipped rather than
+        // returned, which is what quietly handles both discontinuities:
+        //   - over a fold, the wall clock we started inside maps back to its
+        //     first occurrence, already in the past, so the walk moves on and
+        //     the repeated hour is not scheduled a second time;
+        //   - inside a gap, every skipped minute maps to the same gap-end
+        //     instant, so the first of them is returned and the rest are in the
+        //     past by then - one run out of a lost hour, not sixty.
+        if (li && li->utc > start) return li->utc;
+        ++m;
+    }
+    return std::nullopt;
+}
+
+bool cronExpressionValid(const std::string& expr, std::string* error) {
+    return CronExpr::parse(expr, error).has_value();
+}
+
+} // namespace svapi::functions

+ 95 - 0
src/functions/cron.hpp

@@ -0,0 +1,95 @@
+#pragma once
+#include <ctime>
+#include <optional>
+#include <string>
+
+namespace svapi::functions {
+
+/// Cron expression handling, split out of descriptor.cpp so that validating an
+/// expression and firing on it cannot disagree. descriptor.cpp used to carry
+/// its own shape-only parser; a second parser here would be a slow-motion bug,
+/// because a schedule that validates on push and then never matches looks
+/// exactly like a broken scheduler.
+///
+/// Five fields: minute hour day-of-month month day-of-week. Accepts `*`, `n`,
+/// `a-b`, comma lists and `/step` on any of them, plus `JAN`-`DEC` and
+/// `SUN`-`SAT` aliases and `7` as Sunday. No seconds field, no `@hourly`
+/// macros, no `L`/`#` extensions - if that changes, it changes here only.
+///
+/// An expression with no zone is UTC. A function author writing `0 3 * * *`
+/// and no `tz` means 03:00 UTC, not 03:00 wherever the server happens to sit,
+/// because a server that moves hosts must not silently move its schedules.
+/// With a zone - the descriptor's `tz` - the five fields are WALL CLOCK in that
+/// zone, which is what an author who wrote `Europe/Budapest` asked for: 08:00
+/// there all year, not 08:00 in winter and 09:00 in summer.
+struct CronExpr {
+    /// Parse and validate. Returns nullopt for anything malformed; `error`
+    /// names the first problem, in field order, when non-null.
+    static std::optional<CronExpr> parse(const std::string& expr, std::string* error);
+
+    /// Does this expression fire during the minute containing `t`?
+    ///
+    /// Minute resolution: the seconds of `t` are ignored. Day-of-month and
+    /// day-of-week are OR'd when BOTH are restricted, which is what every cron
+    /// implementation does and what an author copying a crontab line expects -
+    /// `0 0 13 * FRI` means the 13th or any Friday, not Friday the 13th.
+    bool matches(std::time_t t) const;
+
+    /// The first minute strictly after `after` at which this fires, or nullopt
+    /// when nothing matches within a year (an impossible date like Feb 30).
+    /// Bounded so a malformed-but-valid expression cannot spin.
+    std::optional<std::time_t> nextFire(std::time_t after) const;
+
+    /// Does this expression fire during the minute containing `t`, read as wall
+    /// clock in `zone`?
+    ///
+    /// An EMPTY zone is UTC and goes down the identical code path as
+    /// `matches()`, so a schedule that carries no `tz` cannot change meaning by
+    /// the mere existence of this overload. An UNKNOWN zone never fires: the
+    /// write path refuses one, so a row that has one is older than that check,
+    /// and a silent UTC fallback would move somebody's 08:00 report by an hour
+    /// and look like it had worked.
+    ///
+    /// The two DST discontinuities are resolved here as
+    /// `functions/timezone.hpp` specifies, and the positions are visible in
+    /// this answer rather than buried in the scheduler:
+    ///   - a SKIPPED wall-clock minute (02:30 on the morning the clocks go
+    ///     forward) matches at the instant the gap ENDS instead of being lost.
+    ///     Every matching minute inside one gap collapses onto that single
+    ///     instant, so an hour of `* 2 * * *` is one run, not sixty.
+    ///   - a REPEATED wall-clock minute (02:30 when they go back) matches on
+    ///     its FIRST occurrence only, so a daily job runs once that day.
+    bool matchesIn(std::time_t t, const std::string& zone) const;
+
+    /// The first minute strictly after `after` at which this fires, read as
+    /// wall clock in `zone`; nullopt when nothing matches within a year or the
+    /// zone is unknown. Empty zone means UTC, exactly as `nextFire()`.
+    ///
+    /// Guaranteed consistent with `matchesIn()` in the same zone: the result
+    /// always matches there, and no minute in between does.
+    std::optional<std::time_t> nextFireIn(std::time_t after, const std::string& zone) const;
+
+private:
+    /// Do the two day fields accept this date, OR rule included? Shared by
+    /// every path - UTC and zone-aware, matching and searching - so the one
+    /// rule everybody gets wrong exists in exactly one place.
+    bool dayMatches(int dayOfMonth, int dayOfWeek) const;
+
+    /// Do all five fields accept this set of civil values?
+    bool fieldsMatch(int month, int dayOfMonth, int dayOfWeek, int hour, int minute) const;
+
+    /// One bit per permitted value, indexed from the field's minimum.
+    bool minute_[60]{};
+    bool hour_[24]{};
+    bool dom_[32]{};    ///< 1-31; index 0 unused
+    bool month_[13]{};  ///< 1-12; index 0 unused
+    bool dow_[7]{};     ///< 0-6, Sunday 0; a 7 in the expression folds to 0
+    bool domRestricted_ = false;
+    bool dowRestricted_ = false;
+};
+
+/// Convenience for the write path: is this a well-formed expression?
+/// `error` names the first problem when non-null.
+bool cronExpressionValid(const std::string& expr, std::string* error);
+
+} // namespace svapi::functions

+ 32 - 133
src/functions/descriptor.cpp

@@ -1,5 +1,10 @@
 #include "functions/descriptor.hpp"
 
+#include "functions/cron.hpp"
+#include "functions/timezone.hpp"
+
+#include "functions/cron.hpp"
+
 #include <algorithm>
 #include <cctype>
 #include <set>
@@ -47,137 +52,6 @@ std::vector<std::string> segments(const std::string& s) {
 
 bool isParamSegment(const std::string& seg) { return !seg.empty() && seg.front() == ':'; }
 
-// ------------------------------------------------------------------- cron
-
-struct CronField {
-    const char* name;
-    int min;
-    int max;
-    /// Three-letter aliases, lowest value first ("jan" = 1, "sun" = 0), or null
-    /// for the numeric-only fields.
-    const char* const* names;
-    int namesBase;
-};
-
-const char* const kMonthNames[] = {"jan", "feb", "mar", "apr", "may", "jun",
-                                   "jul", "aug", "sep", "oct", "nov", "dec", nullptr};
-const char* const kDowNames[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat", nullptr};
-
-const CronField kCronFields[5] = {
-    {"minute", 0, 59, nullptr, 0},
-    {"hour", 0, 23, nullptr, 0},
-    {"day-of-month", 1, 31, nullptr, 0},
-    {"month", 1, 12, kMonthNames, 1},
-    // 7 is Sunday as well, which every cron implementation accepts.
-    {"day-of-week", 0, 7, kDowNames, 0},
-};
-
-/// Resolve one endpoint of a cron range: digits, or a three-letter alias where
-/// the field has them. Returns false when it is neither, or out of range.
-bool cronValue(const std::string& tok, const CronField& f, int& out) {
-    if (tok.empty()) return false;
-    const bool numeric = std::all_of(tok.begin(), tok.end(),
-                                     [](unsigned char c) { return std::isdigit(c) != 0; });
-    if (numeric) {
-        try {
-            out = std::stoi(tok);
-        } catch (const std::exception&) {
-            return false; // absurdly long digit run
-        }
-    } else if (f.names != nullptr) {
-        const std::string low = [&] {
-            std::string s = tok;
-            for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
-            return s;
-        }();
-        out = -1;
-        for (int i = 0; f.names[i] != nullptr; ++i) {
-            if (low == f.names[i]) {
-                out = f.namesBase + i;
-                break;
-            }
-        }
-        if (out < 0) return false;
-    } else {
-        return false;
-    }
-    return out >= f.min && out <= f.max;
-}
-
-/// Shape check for one comma list of a cron field: "*", "5", "1-5", "*/2",
-/// "1-5/2", "0,30". No schedule is computed here - that is the scheduler's job.
-bool cronFieldValid(const std::string& field, const CronField& f) {
-    if (field.empty()) return false;
-    std::size_t pos = 0;
-    while (pos <= field.size()) {
-        const std::size_t comma = field.find(',', pos);
-        const std::string item =
-            field.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
-        if (item.empty()) return false;
-
-        std::string base = item;
-        const std::size_t slash = item.find('/');
-        if (slash != std::string::npos) {
-            base = item.substr(0, slash);
-            const std::string step = item.substr(slash + 1);
-            if (step.empty() || step.find('/') != std::string::npos) return false;
-            if (!std::all_of(step.begin(), step.end(),
-                             [](unsigned char c) { return std::isdigit(c) != 0; }))
-                return false;
-            // Length-capped before converting: parsing must never throw, and no
-            // real step needs more than two digits.
-            if (step.size() > 2) return false;
-            if (std::stoi(step) < 1) return false; // "*/0" would never fire
-        }
-
-        if (base != "*") {
-            const std::size_t dash = base.find('-', 1); // 1: no negative endpoints
-            if (dash == std::string::npos) {
-                int v = 0;
-                if (!cronValue(base, f, v)) return false;
-            } else {
-                int lo = 0;
-                int hi = 0;
-                if (!cronValue(base.substr(0, dash), f, lo)) return false;
-                if (!cronValue(base.substr(dash + 1), f, hi)) return false;
-                if (lo > hi) return false;
-            }
-        }
-
-        if (comma == std::string::npos) break;
-        pos = comma + 1;
-        if (pos == field.size()) return false; // trailing comma
-    }
-    return true;
-}
-
-/// Validate a 5-field cron expression's shape. Returns an empty string when the
-/// expression is well formed, otherwise the first problem found.
-std::string cronError(const std::string& schedule) {
-    std::vector<std::string> fields;
-    std::string cur;
-    for (const char c : schedule) {
-        if (std::isspace(static_cast<unsigned char>(c)) != 0) {
-            if (!cur.empty()) fields.push_back(cur);
-            cur.clear();
-        } else {
-            cur.push_back(c);
-        }
-    }
-    if (!cur.empty()) fields.push_back(cur);
-
-    if (fields.size() != 5)
-        return "cron 'schedule' must have exactly 5 fields (minute hour day-of-month month "
-               "day-of-week), got " +
-               std::to_string(fields.size());
-    for (std::size_t i = 0; i < 5; ++i) {
-        if (!cronFieldValid(fields[i], kCronFields[i]))
-            return std::string("cron 'schedule' field ") + std::to_string(i + 1) + " (" +
-                   kCronFields[i].name + ") is not valid: '" + fields[i] + "'";
-    }
-    return {};
-}
-
 // ------------------------------------------------------------------- http
 
 /// Returns an empty string when `route` is a usable pattern.
@@ -248,6 +122,12 @@ nlohmann::json FunctionDescriptor::toJson() const {
     case TriggerType::Cron:
         j["type"] = "cron";
         j["schedule"] = schedule;
+        // Written only when set, so a UTC schedule does not acquire a zone it
+        // never declared.
+        if (!timezone.empty()) j["tz"] = timezone;
+        break;
+    case TriggerType::Job:
+        j["type"] = "job";
         break;
     case TriggerType::Db:
         j["type"] = "db";
@@ -285,8 +165,10 @@ ParseResult parseDescriptor(const nlohmann::json& on) {
             d.type = TriggerType::Cron;
         } else if (t == "db") {
             d.type = TriggerType::Db;
+        } else if (t == "job") {
+            d.type = TriggerType::Job;
         } else {
-            return fail("'type' must be one of http, cron, db: '" + t + "'");
+            return fail("'type' must be one of http, cron, db, job: '" + t + "'");
         }
     }
 
@@ -303,9 +185,26 @@ ParseResult parseDescriptor(const nlohmann::json& on) {
         if (!on.contains("schedule")) return fail("cron 'schedule' is required");
         if (!on.at("schedule").is_string()) return fail("cron 'schedule' must be a string");
         d.schedule = on.at("schedule").get<std::string>();
-        if (const std::string e = cronError(d.schedule); !e.empty()) return fail(e);
+        // Validated by the engine that will fire it, not by a second parser
+        // living here: a schedule that passes on push and then never matches
+        // would look exactly like a broken scheduler.
+        std::string e;
+        if (!cronExpressionValid(d.schedule, &e)) return fail(e);
+        if (on.contains("tz")) {
+            if (!on.at("tz").is_string()) return fail("cron 'tz' must be an IANA zone name");
+            d.timezone = trim(on.at("tz").get<std::string>());
+            // Refused on push, not at the first fire: an unknown zone that
+            // silently became UTC would move somebody's 08:00 report and look
+            // like it had worked. `tz` used to be dropped here without a word.
+            if (!d.timezone.empty() && !timezoneKnown(d.timezone))
+                return fail("cron 'tz' is not a time zone this host knows: '" + d.timezone + "'");
+        }
         break;
     }
+    case TriggerType::Job:
+        // Nothing required. A job function is reached only by being enqueued,
+        // so it declares no route and no schedule - that is the whole point.
+        break;
     case TriggerType::Db: {
         if (!on.contains("table")) return fail("db 'table' is required");
         if (!on.at("table").is_string()) return fail("db 'table' must be a string");

+ 21 - 4
src/functions/descriptor.hpp

@@ -9,7 +9,11 @@ namespace svapi::functions {
 /// What makes a function run. Slice 1 dispatches only Http, but the whole
 /// vocabulary is parsed now so a script written against a later server is
 /// rejected with a clear message rather than silently treated as an HTTP route.
-enum class TriggerType { Http, Cron, Db };
+/// Job: runs ONLY when something enqueues it - ctx.jobs.enqueue, the HTTP
+/// enqueue route, or a delayed call-back. It has no route and no schedule, so
+/// it cannot be reached by accident, which is what makes it the right home for
+/// slow work: a webhook answers fast and hands the real job to one of these.
+enum class TriggerType { Http, Cron, Db, Job };
 
 enum class DbEvent { Insert, Update, Delete };
 
@@ -33,16 +37,29 @@ struct FunctionDescriptor {
     /// EMPTY MEANS ANY METHOD - it is not "no method allowed".
     std::vector<std::string> methods;
 
-    // Cron. Validated for shape only; nothing here schedules anything.
+    // Cron.
     std::string schedule;
+    /// IANA zone the schedule is read in; empty means UTC.
+    ///
+    /// Load bearing, and it used to be silently dropped: 08:00 in Budapest is
+    /// 06:00 UTC in winter and 07:00 in summer, so a schedule without a zone
+    /// shifts by an hour twice a year. Validated against the host tz database
+    /// at write time, so an unknown zone is refused on push rather than at the
+    /// first fire.
+    std::string timezone;
 
     // Db
     std::string table;
     DbEvent event = DbEvent::Insert;
 
     // Common
-    /// 0 means "not declared"; the runner then applies its configured default.
-    /// A declared value is still clamped to the configured maximum elsewhere.
+    /// Per-script wall-clock budget. 0 means "not declared", and the runner
+    /// applies its default.
+    ///
+    /// Clamped to a ceiling that depends on HOW the function runs: an HTTP
+    /// route answers a caller who is holding a socket open, while a job run has
+    /// nobody waiting and may legitimately take minutes. One ceiling for both
+    /// made every agent turn and every uncached embedding impossible.
     long long timeoutMs = 0;
     bool singleFlight = false;
 

+ 188 - 0
src/functions/timezone.cpp

@@ -0,0 +1,188 @@
+#include "functions/timezone.hpp"
+
+#include <chrono>
+#include <exception>
+#include <mutex>
+#include <unordered_map>
+
+namespace svapi::functions {
+namespace {
+
+// Named individually rather than `using namespace std::chrono`, because
+// std::chrono::year, ::month and ::day are precisely the names utcFromLocal
+// takes as parameters: a wholesale directive would have those parameters shadow
+// the calendar types, and `month{...}` would stop compiling for a reason that
+// reads like nonsense.
+using std::chrono::days;
+using std::chrono::floor;
+using std::chrono::hh_mm_ss;
+using std::chrono::hours;
+using std::chrono::January;
+using std::chrono::local_days;
+using std::chrono::local_info;
+using std::chrono::local_seconds;
+using std::chrono::locate_zone;
+using std::chrono::minutes;
+using std::chrono::seconds;
+using std::chrono::sys_days;
+using std::chrono::sys_info;
+using std::chrono::sys_seconds;
+using std::chrono::time_zone;
+using std::chrono::weekday;
+using std::chrono::year_month_day;
+
+/// Look a zone up once and remember the answer, including the negative one.
+///
+/// Two reasons for the cache. locate_zone() signals an unknown zone by
+/// throwing, and the scheduler asks about every cron function on every tick, so
+/// one bad row would otherwise construct and unwind an exception three times a
+/// minute forever. And the pointers are stable for the lifetime of the process:
+/// the entries belong to the tzdb list, which only ever grows at the front when
+/// someone calls reload_tzdb(), which this service never does. Caching a
+/// pointer would be wrong in a process that reloads; this one does not, and the
+/// alternative is a string lookup inside the scheduler's hot loop.
+const time_zone* lookupZone(const std::string& zone) {
+    // An empty name is not a zone. Checked before the cache so the empty string
+    // never becomes an entry: callers use "" to mean UTC, and that decision
+    // belongs to them, not to a table that would answer "unknown" for it.
+    if (zone.empty()) return nullptr;
+
+    static std::mutex m;
+    static std::unordered_map<std::string, const time_zone*> cache;
+
+    const std::lock_guard<std::mutex> lk(m);
+    const auto it = cache.find(zone);
+    if (it != cache.end()) return it->second;
+
+    const time_zone* z = nullptr;
+    try {
+        z = locate_zone(zone);
+    } catch (const std::exception&) {
+        // Includes a missing or unreadable tz database, not only a typo in the
+        // name. Either way the answer is "this host cannot schedule in that
+        // zone", which is what the caller has to act on.
+        z = nullptr;
+    }
+    cache.emplace(zone, z);
+    return z;
+}
+
+} // namespace
+
+bool timezoneKnown(const std::string& zone) { return lookupZone(zone) != nullptr; }
+
+std::optional<ZoneParts> zonePartsAt(const std::string& zone, std::time_t utc) {
+    const time_zone* z = lookupZone(zone);
+    if (z == nullptr) return std::nullopt;
+
+    const sys_seconds instant{seconds{utc}};
+    sys_info info;
+    try {
+        info = z->get_info(instant);
+    } catch (const std::exception&) {
+        // get_info throws for an instant outside the range the zone's rules
+        // cover. A timestamp we cannot place is not a timestamp we may guess
+        // at, so decline rather than return UTC parts.
+        return std::nullopt;
+    }
+
+    // The whole offset, DST included, is what turns an instant into wall clock.
+    // Added as seconds and not as hours: a zone can be offset by 45 minutes
+    // (Asia/Kathmandu is +05:45), and an implementation that rounded to hours
+    // would be wrong only there, which is the hardest kind of wrong to notice.
+    const local_seconds localTime{instant.time_since_epoch() + info.offset};
+    const local_days localDay = floor<days>(localTime);
+    const year_month_day ymd{localDay};
+    const hh_mm_ss<seconds> hms{localTime - localDay};
+
+    ZoneParts p;
+    p.year = static_cast<int>(ymd.year());
+    p.month = static_cast<int>(static_cast<unsigned>(ymd.month()));
+    p.day = static_cast<int>(static_cast<unsigned>(ymd.day()));
+    p.hour = static_cast<int>(hms.hours().count());
+    p.minute = static_cast<int>(hms.minutes().count());
+    p.second = static_cast<int>(hms.seconds().count());
+    // The weekday and yearday of the LOCAL date, which is the point: 23:30 UTC
+    // is already Thursday in Budapest, and a Thursday-only schedule has to
+    // agree with the calendar on the author's wall.
+    p.weekday = static_cast<int>(weekday{sys_days{ymd}}.c_encoding());
+    p.yearday =
+        static_cast<int>((sys_days{ymd} - sys_days{ymd.year() / January / 1}).count() + 1);
+    p.offsetSec = info.offset.count();
+    // `save` is the DST adjustment itself, so a non-zero save is the only
+    // honest definition of "is DST in effect"; comparing offsets against a
+    // standard offset we would have to guess at is not.
+    p.dst = info.save != minutes{0};
+    p.abbrev = info.abbrev;
+    return p;
+}
+
+std::optional<LocalInstant> utcFromLocal(const std::string& zone, int year, int month, int day,
+                                         int hour, int minute, int second) {
+    const time_zone* z = lookupZone(zone);
+    if (z == nullptr) return std::nullopt;
+
+    // A date that does not exist is refused rather than normalised. Feb 30 is
+    // exactly what "0 0 30 2 *" asks for, and silently turning it into March 2
+    // would make an impossible schedule fire on a day the author never named.
+    if (month < 1 || month > 12 || day < 1) return std::nullopt;
+    const year_month_day ymd{std::chrono::year{year} /
+                             std::chrono::month{static_cast<unsigned>(month)} /
+                             std::chrono::day{static_cast<unsigned>(day)}};
+    if (!ymd.ok()) return std::nullopt;
+    // Hours and minutes outside their range are a caller bug, not data; the
+    // same refusal keeps them from wrapping into the next day unnoticed.
+    if (hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59)
+        return std::nullopt;
+
+    const local_seconds localTime = local_days{ymd} + hours{hour} + minutes{minute} +
+                                    seconds{second};
+
+    local_info info;
+    try {
+        info = z->get_info(localTime);
+    } catch (const std::exception&) {
+        return std::nullopt;
+    }
+
+    LocalInstant out;
+    switch (info.result) {
+    case local_info::unique:
+        out.utc = static_cast<std::time_t>(
+            (localTime.time_since_epoch() - info.first.offset).count());
+        out.existed = true;
+        out.ambiguous = false;
+        return out;
+
+    case local_info::nonexistent:
+        // The clocks went forward over this wall-clock time, so it never
+        // happened. `second.begin` is the instant the gap ends - the first
+        // moment that exists again - and returning it is what makes a schedule
+        // land once instead of vanishing for the year. Every minute inside one
+        // gap answers with this same instant, which is also what keeps a lost
+        // hour of matching minutes down to a single run.
+        out.utc = static_cast<std::time_t>(info.second.begin.time_since_epoch().count());
+        out.existed = false;
+        out.ambiguous = false;
+        return out;
+
+    case local_info::ambiguous:
+        // The clocks went back, so this wall clock happened twice. The FIRST
+        // occurrence - still under the pre-transition offset, `first` - is the
+        // answer, so a daily job runs once that day. Taking the second would
+        // delay it by the DST hour; taking both would run it twice, which for
+        // anything that sends or charges is the worse failure.
+        out.utc = static_cast<std::time_t>(
+            (localTime.time_since_epoch() - info.first.offset).count());
+        out.existed = true;
+        out.ambiguous = true;
+        return out;
+
+    default:
+        // local_info carries no other result today. Declining beats inventing
+        // an instant for a classification we do not understand.
+        return std::nullopt;
+    }
+}
+
+} // namespace svapi::functions

+ 60 - 0
src/functions/timezone.hpp

@@ -0,0 +1,60 @@
+#pragma once
+#include <ctime>
+#include <optional>
+#include <string>
+
+namespace svapi::functions {
+
+/// IANA time zone handling, backed by the system tz database through
+/// std::chrono. One implementation, because two things need it and they must
+/// agree: a cron schedule declaring `tz`, and ctx.time for a function that has
+/// to render or reason about local time.
+///
+/// Why this exists at all: QuickJS (quickjs-ng) ships no Intl and no ICU, so a
+/// function has no way to know that 08:00 in Budapest is 06:00 UTC in winter
+/// and 07:00 in summer. Without it a daily schedule silently shifts by an hour
+/// twice a year, which is the kind of bug that looks fine for five months.
+///
+/// Requires tzdata on the host. Every function here answers nullopt for an
+/// unknown zone rather than falling back to UTC: a silent fallback would move
+/// somebody's 08:00 report and look like it worked.
+
+/// Is this a zone the host knows? Used to validate a descriptor at write time,
+/// so an unknown zone is refused on push instead of at the first fire.
+bool timezoneKnown(const std::string& zone);
+
+/// Civil (wall-clock) fields in `zone` at the given UTC instant.
+struct ZoneParts {
+    int year = 0;
+    int month = 0;    ///< 1-12
+    int day = 0;      ///< 1-31
+    int hour = 0;     ///< 0-23
+    int minute = 0;
+    int second = 0;
+    int weekday = 0;  ///< 0 = Sunday, matching cron's day-of-week
+    int yearday = 0;  ///< 1-366
+    long long offsetSec = 0;  ///< total offset from UTC, DST included
+    bool dst = false;
+    std::string abbrev;  ///< e.g. "CET", "CEST"
+};
+std::optional<ZoneParts> zonePartsAt(const std::string& zone, std::time_t utc);
+
+/// The UTC instant for a wall-clock time in `zone`.
+///
+/// DST makes this ambiguous in two ways, and a scheduler has to take a position
+/// on both rather than let the library choose:
+///   - a SKIPPED time (02:30 on the morning the clocks go forward) does not
+///     exist; `existed` comes back false and the instant returned is the moment
+///     the gap ends, so a schedule lands once rather than being lost.
+///   - a REPEATED time (02:30 on the morning they go back) happens twice;
+///     the FIRST occurrence is returned and `ambiguous` is true, so a daily job
+///     runs once that day instead of twice.
+struct LocalInstant {
+    std::time_t utc = 0;
+    bool existed = true;
+    bool ambiguous = false;
+};
+std::optional<LocalInstant> utcFromLocal(const std::string& zone, int year, int month, int day,
+                                         int hour, int minute, int second);
+
+} // namespace svapi::functions

+ 132 - 0
src/functions/wall_budget.hpp

@@ -0,0 +1,132 @@
+#pragma once
+#include <algorithm>
+#include <cstdint>
+#include <string>
+#include <string_view>
+
+/// How much wall time one function run gets.
+///
+/// This exists because a single ceiling cannot serve both callers. An HTTP run
+/// is behind a socket somebody is waiting on, so its budget is a latency
+/// decision and belongs in the low seconds. A cron or event job has no client
+/// at all, and the work it is actually asked to do - an LLM call, an uncached
+/// embedding search - routinely needs tens of seconds. One number for both
+/// means either the HTTP route can hang for two minutes or the job gets killed
+/// before it can finish; neither is acceptable, so there are two ceilings and a
+/// run says which one applies to it.
+///
+/// Header-only and pure: no I/O, no clock, no global state. The runner's
+/// protocol layer and the server both include it, and neither may grow a
+/// dependency from doing so.
+namespace svapi::functions {
+
+/// What triggered a run, as far as its time budget is concerned.
+///
+/// Deliberately NOT derived from the descriptor's TriggerType. A function
+/// declared `type: 'job'` can be invoked by hand for debugging, and when it is,
+/// it is running inside an HTTP request that will be waited on - so it gets the
+/// HTTP budget. The kind describes how this run was started, not what the
+/// script says about itself.
+enum class RunKind { Http, Job };
+
+/// The last-resort ceiling, applied when nothing is configured. A missing or
+/// zero ceiling must never mean "unlimited": that would turn a half-written
+/// config into an unbounded run holding a pooled runtime.
+constexpr int64_t kFallbackWallCeilingMs = 2000;
+
+inline std::string_view runKindName(RunKind kind) {
+    return kind == RunKind::Job ? "job" : "http";
+}
+
+/// Read a run kind off the wire. Anything unrecognised - including a missing
+/// value - yields `fallback`, and every caller passes RunKind::Http for it:
+/// guessing wrong towards the SHORTER budget costs a slow run, guessing wrong
+/// towards the longer one lets an HTTP request pin a runtime for minutes.
+inline RunKind parseRunKind(std::string_view name, RunKind fallback) {
+    if (name == "job") return RunKind::Job;
+    if (name == "http") return RunKind::Http;
+    return fallback;
+}
+
+/// Everything that has a say in one run's budget. All times are milliseconds,
+/// and 0 consistently means "not stated" rather than "zero time allowed".
+struct WallBudgetRequest {
+    /// How this run was triggered, which selects the ceiling.
+    RunKind kind = RunKind::Http;
+    /// The descriptor's `timeoutMs`. 0 means the script declared none.
+    int64_t declaredMs = 0;
+    /// The runner's configured default for an undeclared run. 0 means "as much
+    /// as the applicable cap allows".
+    int64_t defaultMs = 0;
+    /// The project's admin-set maximum. 0 means the project has none, so the
+    /// ceiling is the only cap. This is what stops one tenant pinning pool
+    /// runtimes for minutes at a time with a 120 s descriptor.
+    int64_t projectMaxMs = 0;
+    /// The two configured ceilings.
+    int64_t httpCeilingMs = 0;
+    int64_t jobCeilingMs = 0;
+    /// The engine's absolute ceiling (JsLimits::wall_time_ms). Nothing can be
+    /// granted above it, because JsRuntime::run clamps any override to it
+    /// anyway - stating it here keeps the number we report equal to the number
+    /// the engine will enforce.
+    int64_t hardCeilingMs = 0;
+};
+
+struct WallBudget {
+    /// What to pass to JsRuntime::run as the wall-time override. Always >= 1.
+    int64_t effectiveMs = 0;
+    /// The ceiling that applied to this kind of run, after the hard ceiling.
+    /// Reported so an operator can see WHICH limit a run was measured against.
+    int64_t ceilingMs = 0;
+    /// Which cap actually reduced an explicitly requested budget. Both false
+    /// when the request was honoured in full, or when nothing was requested.
+    /// They are separate because the remedies differ: one is the operator's
+    /// runner config, the other is the project's maximum.
+    bool clampedByCeiling = false;
+    bool clampedByProjectMax = false;
+};
+
+/// Resolve one run's wall budget. Precedence, in order:
+///
+///   1. The ceiling for this kind of run (job or HTTP), itself clamped to the
+///      engine's hard ceiling, falling back to kFallbackWallCeilingMs when
+///      nothing is configured.
+///   2. The cap: the project maximum when it is set and lower, else the
+///      ceiling. A project maximum can only ever narrow.
+///   3. The request: the descriptor's timeoutMs, else the configured default,
+///      else the cap.
+///   4. effective = min(request, cap), never below 1 ms.
+///
+/// So a descriptor asking for 120 s gets 120 s on a job run with a 120 s
+/// ceiling, 2 s on an HTTP run with a 2 s ceiling, and whatever the project
+/// allows when that is lower than either.
+inline WallBudget resolveWallBudget(const WallBudgetRequest& in) {
+    WallBudget out;
+
+    int64_t ceiling = in.kind == RunKind::Job ? in.jobCeilingMs : in.httpCeilingMs;
+    if (ceiling <= 0) ceiling = in.hardCeilingMs;
+    if (ceiling <= 0) ceiling = kFallbackWallCeilingMs;
+    if (in.hardCeilingMs > 0) ceiling = std::min(ceiling, in.hardCeilingMs);
+    out.ceilingMs = ceiling;
+
+    const bool projectCaps = in.projectMaxMs > 0 && in.projectMaxMs < ceiling;
+    const int64_t cap = projectCaps ? in.projectMaxMs : ceiling;
+
+    // An explicit request is one somebody wrote down - in the script or in the
+    // runner config. Only those can be "clamped"; an absent request takes the
+    // cap by definition and reporting that as a clamp would be noise.
+    const bool explicitRequest = in.declaredMs > 0 || in.defaultMs > 0;
+    const int64_t requested =
+        in.declaredMs > 0 ? in.declaredMs : (in.defaultMs > 0 ? in.defaultMs : cap);
+
+    out.effectiveMs = std::min(requested, cap);
+    if (out.effectiveMs < 1) out.effectiveMs = 1;
+
+    if (explicitRequest && requested > cap) {
+        if (projectCaps) out.clampedByProjectMax = true;
+        else out.clampedByCeiling = true;
+    }
+    return out;
+}
+
+} // namespace svapi::functions

+ 212 - 71
src/handlers/documents.cpp

@@ -1,5 +1,6 @@
 #include "collection_registry.hpp"
 #include "db_errors.hpp"
+#include "documents_util.hpp"
 #include "errors.hpp"
 #include "filters.hpp"
 #include "json_http.hpp"
@@ -12,52 +13,30 @@
 namespace svapi {
 namespace {
 
-/// The document carried by a write request, accepting both shapes:
-///
-///   {"data": {...}}   a wrapper, unwrapped here
-///   {...}             the document itself
-///
-/// `id` is never a field: POST takes the document id from the body, PUT and
-/// PATCH from the URL, so it is removed either way.
-///
-/// A `data` key next to any OTHER top-level key is refused. Taking body["data"]
-/// and discarding the siblings loses them silently, which is how a caller ends
-/// up missing fields with nothing in the response to say so.
-///
-/// A document whose own top-level field is named `data` is still writable by
-/// nesting it once: {"data": {"data": ...}}.
-nlohmann::json documentBody(const nlohmann::json& body) {
-    if (!body.is_object())
-        throw ApiError(ErrCode::Unprocessable, "validation", "body must be a JSON object");
-
-    if (body.contains("data")) {
-        std::vector<std::string> siblings;
-        for (auto it = body.begin(); it != body.end(); ++it)
-            if (it.key() != "data" && it.key() != "id") siblings.push_back(it.key());
-        if (!siblings.empty()) {
-            std::string list;
-            for (const auto& k : siblings) list += (list.empty() ? "" : ", ") + k;
-            throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
-                           "'data' is treated as a wrapper and must be the only top-level field, "
-                           "but found alongside: " + list +
-                           ". Send the document on its own, or nest it as {\"data\":{\"data\":...}}.");
-        }
-        nlohmann::json data = body["data"];
-        if (data.is_object() && data.contains("id")) data.erase("id");
-        return data;
-    }
-
-    nlohmann::json doc = body;
-    if (doc.contains("id")) doc.erase("id");
-    return doc;
-}
-// Authorize + verify the collection exists; returns the qualified collection name.
-std::string scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
-    ApiKey k = requireKey(*d, req);
-    std::string project = req.matches[projIdx], name = req.matches[collIdx];
-    requireCapability(*d, k, req, project, name, op);
-    if (!d->registry.get(project, name)) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
-    return qualify(project, name);
+// Everything a document route needs about its target once the caller has been
+// authorized: the key (PUT re-checks it on the create branch), the unqualified
+// names for anything caller-facing, the qualified name for the database, and
+// the registry entry, which carries the collection's kind.
+struct Target {
+    ApiKey         key;
+    std::string    project;
+    std::string    name;
+    std::string    qualified;
+    CollectionMeta meta;
+};
+
+// Authorize + verify the collection exists.
+Target scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
+    Target t;
+    t.key = requireKey(*d, req);
+    t.project = req.matches[projIdx];
+    t.name = req.matches[collIdx];
+    requireCapability(*d, t.key, req, t.project, t.name, op);
+    auto meta = d->registry.get(t.project, t.name);
+    if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
+    t.meta = *meta;
+    t.qualified = qualify(t.project, t.name);
+    return t;
 }
 
 // Parses ?ttl_seconds=. Returns nullopt when absent - the caller must
@@ -72,19 +51,49 @@ std::optional<uint32_t> ttlParam(const httplib::Request& req) {
         throw ApiError(ErrCode::Unprocessable, "validation", "ttl_seconds must be a non-negative integer");
     return (uint32_t)wide;
 }
+
+// Parses ?if_version=. Absent means an unconditional write.
+std::optional<uint64_t> ifVersionParam(const httplib::Request& req) {
+    if (!req.has_param("if_version")) return std::nullopt;
+    return parseVersionValue(req.get_param_value("if_version"));
 }
+
+// 409 for the one case the database cannot report: the version was already
+// wrong when we read it, so no write was attempted and there is no failure to
+// translate. A conflict the DATABASE refuses comes back as ErrorCode::Aborted
+// carrying the version it found, and goes through conditionalFailure() below.
+ApiError versionConflict(uint64_t expected, std::optional<uint64_t> current) {
+    nlohmann::json det{{"expected_version", expected}};
+    if (current) det["current_version"] = *current;
+    return ApiError(ErrCode::Conflict, "version_conflict",
+                    "the document is not at the expected version", det);
+}
+
+// A failed conditional write, with both halves of the story.
+//
+// The database reports the version it FOUND; only the caller knows which
+// version it ASKED for. Neither alone lets a client decide what to do, so they
+// are merged here rather than leaving the caller to remember its own request.
+ApiError conditionalFailure(const smartbotic::database::Client::FailureDetail& detail,
+                            uint64_t expected) {
+    ApiError e = apiErrorFor(detail, "no such document");
+    e.details["expected_version"] = expected;
+    return e;
+}
+
+}  // namespace
 void registerDocumentRoutes(ApiServer& s) {
     auto& svr = s.raw(); ServerDeps* d = &s.deps();
 
     svr.Post(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
-        std::string c = scoped(d, req, 1, 2, KeyOp::Insert);
+        Target t = scoped(d, req, 1, 2, KeyOp::Insert);
         auto body = bodyJson(req);
         std::string id = body.value("id", "");
         nlohmann::json data = documentBody(body);
         const uint32_t ttl = ttlParam(req).value_or(0);
         std::string newId;
         try {
-            newId = d->db.client().insert(c, data, id, ttl);
+            newId = d->db.client().insert(t.qualified, data, id, ttl);
         } catch (const smartbotic::database::Client::Error& e) {
             throw apiErrorFor(e);
         }
@@ -93,14 +102,21 @@ void registerDocumentRoutes(ApiServer& s) {
     });
 
     svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        std::string c = scoped(d, req, 1, 2, KeyOp::Read);
-        auto doc = d->db.client().get(c, req.matches[3]);
+        Target t = scoped(d, req, 1, 2, KeyOp::Read);
+        auto doc = d->db.client().get(t.qualified, req.matches[3]);
         if (!doc) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
+        // The body is the stored document plus the database's read-only
+        // metadata (`_id`, `_version`, `_created_at`, `_updated_at`,
+        // `_created_by`, `_updated_by`). `_version` is the value `?if_version=`
+        // takes, so it is also echoed as an ETag: that is where an HTTP client
+        // or cache looks for a resource version, and it costs nothing here.
+        if (auto v = documentVersion(*doc))
+            res.set_header("ETag", "\"" + std::to_string(*v) + "\"");
         sendJson(res, 200, *doc);
     });
 
     svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents)", [d](const httplib::Request& req, httplib::Response& res) {
-        std::string c = scoped(d, req, 1, 2, KeyOp::List);
+        Target t = scoped(d, req, 1, 2, KeyOp::List);
         smartbotic::database::Client::QueryOptions opts;
         auto range = req.params.equal_range("filter");
         for (auto it = range.first; it != range.second; ++it) opts.filters.push_back(parseFilter(it->second));
@@ -112,47 +128,172 @@ void registerDocumentRoutes(ApiServer& s) {
         if (req.has_param("offset")) opts.offset = parseUInt(req.get_param_value("offset"), "offset");
         if (req.has_param("sort"))   opts.sortField = req.get_param_value("sort");
         if (req.has_param("desc"))   opts.sortDescending = (req.get_param_value("desc") == "true");
-        auto docs = d->db.client().find(c, opts);
+        // Each listed document 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 round trip per row.
+        auto docs = d->db.client().find(t.qualified, opts);
         sendJson(res, 200, {{"documents", docs}, {"count", docs.size()}});
     });
 
     svr.Patch(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3];
-        if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
-        nlohmann::json patchBody = documentBody(bodyJson(req));
+        Target t = scoped(d, req, 1, 2, KeyOp::Update);
+        std::string id = req.matches[3];
         const auto ttl = ttlParam(req);
-        smartbotic::database::Client::Failure failure;
-        uint64_t v = ttl ? d->db.client().patchWithTtl(c, id, patchBody, *ttl, failure)
-                          : d->db.client().patch(c, id, patchBody, failure);
-        if (v == 0) throw apiErrorFor(failure, "no such document");
-        sendJson(res, 200, {{"id", id}, {"version", v}});
+        const auto ifVersion = ifVersionParam(req);
+        nlohmann::json patchBody = documentBody(bodyJson(req));
+
+        if (!ifVersion) {
+            // A patch is a server-side merge: it reads nothing out and cannot
+            // lose a concurrent writer's fields. The existence probe stays a
+            // probe rather than a read, so the common path does not pay for
+            // fetching a document it does not look at.
+            if (!d->db.client().exists(t.qualified, id))
+                throw ApiError(ErrCode::NotFound, "not_found", "no such document");
+            smartbotic::database::Client::Failure failure;
+            uint64_t v = ttl ? d->db.client().patchWithTtl(t.qualified, id, patchBody, *ttl, failure)
+                             : d->db.client().patch(t.qualified, id, patchBody, failure);
+            if (v == 0) throw apiErrorFor(failure, "no such document");
+            sendJson(res, 200, {{"id", id}, {"version", v}});
+            return;
+        }
+
+        // Conditional patch, in ONE call. The database applies the merge and
+        // checks the version server-side, so there is no window at all - not
+        // even the narrow one a read-merge-write with a version check leaves,
+        // and no need to reconstruct the server's merge semantics here.
+        //
+        // The one thing it cannot carry is an expiry: there is no conditional
+        // patch-with-TTL, and silently dropping one of the two would be worse
+        // than refusing.
+        if (ttl)
+            throw ApiError(ErrCode::Unprocessable, "conditional_unsupported",
+                           "if_version cannot be combined with ttl_seconds on PATCH: "
+                           "set the expiry in a separate unconditional request");
+
+        smartbotic::database::Client::FailureDetail detail;
+        const uint64_t newVersion =
+            d->db.client().patchIfVersion(t.qualified, id, patchBody, *ifVersion, detail);
+        // A stale version is Aborted with reason "version_conflict" and the
+        // version it actually found, so the caller is told what to re-read
+        // rather than being left to guess.
+        if (newVersion == 0) throw conditionalFailure(detail, *ifVersion);
+        sendJson(res, 200, {{"id", id}, {"version", newVersion}});
     });
 
     svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3];
-        if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
-        smartbotic::database::Client::Failure failure;
-        if (!d->db.client().update(c, id, documentBody(bodyJson(req)), failure))
-            throw apiErrorFor(failure, "no such document");
-        sendJson(res, 200, {{"id", id}});
+        Target t = scoped(d, req, 1, 2, KeyOp::Update);
+        std::string id = req.matches[3];
+        const auto ifVersion = ifVersionParam(req);
+        nlohmann::json data = documentBody(bodyJson(req));
+
+        // PUT creates the document when it is absent, which is what the method
+        // means and what this API has always documented. The alternative - 404
+        // plus a separate upsert route - would give PUT a meaning HTTP does not
+        // have and leave callers keyed by an id they receive from elsewhere (a
+        // provider's call id, say) doing a probe request before every write.
+        // It grants no new power either: POST already stores at a
+        // caller-supplied id.
+        //
+        // PATCH deliberately keeps its 404: merging fields into a document that
+        // does not exist has no defined result, and a PATCH body is not a whole
+        // document, so creating from one would store something the caller never
+        // described.
+        for (int attempt = 0;; ++attempt) {
+            // A read, not an exists() probe: the version comes out of the same
+            // call, and the replace path needed a read anyway (Client::update
+            // does one internally).
+            auto current = d->db.client().get(t.qualified, id);
+
+            if (!current) {
+                if (ifVersion) {
+                    // A conditional write never creates: there is no version to
+                    // match, and answering 201 would make `?if_version=` look
+                    // like it had been honoured.
+                    throw ApiError(ErrCode::NotFound, "not_found", "no such document");
+                }
+                // Creating is an insert however it is spelled. A key whose
+                // scope grants `update` but not `insert` must not gain the
+                // ability to create rows by using PUT instead of POST. Checked
+                // against the scope directly rather than through
+                // requireCapability(), which also spends a rate-limit token:
+                // this request already spent one, and one request must cost one
+                // token however many rules it is measured against.
+                if (t.key.scope && !t.key.scope->findRule(t.name, KeyOp::Insert))
+                    throw ApiError(ErrCode::Forbidden, "forbidden",
+                                   "scope permits update but not insert, so PUT may only "
+                                   "replace a document that already exists");
+                try {
+                    d->db.client().insert(t.qualified, data, id, 0);
+                } catch (const smartbotic::database::Client::Error& e) {
+                    // Another writer created this id between our read and the
+                    // insert. The request still means "make the document look
+                    // like this", so one retry takes the replace branch.
+                    //
+                    // Narrowly matched: an id collision reaches us as a generic
+                    // internal error naming the id, while a unique-index
+                    // collision is AlreadyExists and must surface at once -
+                    // retrying that would only refuse again, one 409 later.
+                    const bool idTaken =
+                        e.code() == smartbotic::database::Client::ErrorCode::Internal &&
+                        std::string(e.what()).find("already exists") != std::string::npos;
+                    if (idTaken && attempt == 0) continue;
+                    throw apiErrorFor(e);
+                }
+                // An insert always produces version 1.
+                res.set_header("Location", req.path);
+                sendJson(res, 201, {{"id", id}, {"created", true}, {"version", 1}});
+                return;
+            }
+
+            auto have = documentVersion(*current);
+            if (!have)
+                throw ApiError(ErrCode::Unavailable, "db_error",
+                               "the database did not report a document version");
+            if (ifVersion && *have != *ifVersion) throw versionConflict(*ifVersion, have);
+
+            // Version-checked even when the caller named no version: that is
+            // what Client::update() does internally, and doing it here means
+            // the new version is known without a second read. Without a named
+            // version a conflict is another writer and is retried; with one it
+            // is the answer the caller asked for.
+            const uint64_t expected = ifVersion.value_or(*have);
+            smartbotic::database::Client::FailureDetail detail;
+            if (d->db.client().updateIfVersion(t.qualified, id, data, expected, detail)) {
+                sendJson(res, 200, {{"id", id}, {"created", false}, {"version", expected + 1}});
+                return;
+            }
+            // Aborted is the database saying the version moved, and it reports
+            // the version it actually found - no second read needed, and no
+            // guessing from the message text.
+            if (detail.code == smartbotic::database::Client::ErrorCode::Aborted) {
+                // An explicit if_version is the caller's condition: tell it.
+                if (ifVersion) throw conditionalFailure(detail, *ifVersion);
+                // No if_version: the replace simply lost a race. Re-read and
+                // write again, and after a bounded number of tries report the
+                // conflict rather than blaming the database with a 503.
+                if (attempt < 3) continue;
+                throw conditionalFailure(detail, expected);
+            }
+            throw apiErrorFor(detail, "no such document");
+        }
     });
 
     svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
-        std::string c = scoped(d, req, 1, 2, KeyOp::Delete); std::string id = req.matches[3];
-        std::string project = req.matches[1];
+        Target t = scoped(d, req, 1, 2, KeyOp::Delete);
+        std::string id = req.matches[3];
         smartbotic::database::Client::Failure failure;
-        if (!d->db.client().remove(c, id, failure)) {
+        if (!d->db.client().remove(t.qualified, id, failure)) {
             // A restrict relation is the one refusal a caller can act on, so it
             // gets 409 plus the impact list rather than a generic failure. Only
             // ask for the impacts when the database says a precondition failed;
             // previously every failure took this path and then answered 404,
             // which was wrong for a transport error.
             if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
-                auto why = d->db.client().describeDelete(c, id);
+                auto why = d->db.client().describeDelete(t.qualified, id);
                 if (why.success && why.wouldBeBlocked)
                     throw ApiError(ErrCode::Conflict, "relation_restricted",
                                    "delete blocked by a relation",
-                                   {{"impacts", impactsJson(project, why)}});
+                                   {{"impacts", impactsJson(t.project, why)}});
             }
             throw apiErrorFor(failure, "no such document");
         }

+ 139 - 0
src/handlers/project_secrets.cpp

@@ -0,0 +1,139 @@
+// Per-project function secrets over the API.
+//
+// The problem these routes solve: a secret a function needs - a bot token, a
+// provider key, a webhook signing secret - could only be set by editing the
+// runner's environment file on the host, so every one of them needed shell
+// access to a machine the project's own people do not have.
+//
+// Authorization is split deliberately:
+//   WRITE and DELETE are admin-only. A secret value is a live credential that
+//   every function in the project then executes with, which puts it in the same
+//   class as a function's policy and the egress blocklist - the things only an
+//   admin may change because they hand running code new power. It is also
+//   write-only storage: nobody can read back what was overwritten, so a
+//   mistaken write is unrecoverable, and the narrower credential is the right
+//   one to require.
+//   LIST and GET are project-manage. They return names and timestamps only, and
+//   a function author needs to know which names their code may read; a
+//   project-manage caller can already read every function's source in the
+//   project, so the set of names tells them nothing new.
+#include "db_gateway.hpp"
+#include "errors.hpp"
+#include "json_http.hpp"
+#include "project_secret_store.hpp"
+#include "project_secrets.hpp"
+#include "server.hpp"
+#include <algorithm>
+
+namespace svapi {
+namespace {
+
+/// Confirm the project exists before anything qualifies a collection with its
+/// name. An admin key carries `projects:["*"]`, so without this a typo would
+/// silently create a secrets collection for a project that does not exist, and
+/// the secret would sit there unreadable by anyone.
+void requireExistingProject(ServerDeps* d, const std::string& project) {
+    const std::vector<std::string> all = d->db.listProjects();
+    if (std::find(all.begin(), all.end(), project) == all.end())
+        throw ApiError(ErrCode::NotFound, "not_found", "no such project");
+}
+
+std::string secretNameParam(const httplib::Request& req) {
+    const std::string name = req.matches[2];
+    if (!validSecretName(name))
+        throw ApiError(ErrCode::Unprocessable, "validation",
+                       "secret name must match [A-Z_][A-Z0-9_]* and be at most " +
+                           std::to_string(kMaxSecretNameLength) + " characters");
+    return name;
+}
+
+} // namespace
+
+void registerProjectSecretRoutes(ApiServer& s) {
+    auto& svr = s.raw(); ServerDeps* d = &s.deps();
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/secrets)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireProjectManage(requireKey(*d, req), project);
+        requireExistingProject(d, project);
+
+        ProjectSecretStore store(d->db);
+        std::vector<ProjectSecret> rows = store.list(project);
+        std::sort(rows.begin(), rows.end(),
+                  [](const ProjectSecret& a, const ProjectSecret& b) { return a.name < b.name; });
+        nlohmann::json arr = nlohmann::json::array();
+        for (const ProjectSecret& row : rows) arr.push_back(row.summaryJson());
+        sendJson(res, 200, {{"project", project},
+                            {"secrets", arr},
+                            {"count", arr.size()},
+                            {"max_secrets", kMaxSecretsPerProject},
+                            {"max_value_bytes", kMaxSecretValueBytes}});
+    });
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/secrets/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireProjectManage(requireKey(*d, req), project);
+        requireExistingProject(d, project);
+        const std::string name = secretNameParam(req);
+
+        ProjectSecretStore store(d->db);
+        std::optional<ProjectSecret> row = store.get(project, name);
+        if (!row) throw ApiError(ErrCode::NotFound, "not_found", "no such secret");
+        sendJson(res, 200, row->summaryJson());
+    });
+
+    svr.Put(R"(/api/v1/projects/([^/]+)/secrets/([^/]+))",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireAdmin(requireKey(*d, req));
+        requireExistingProject(d, project);
+        const std::string name = secretNameParam(req);
+
+        auto body = bodyJson(req);
+        if (!body.is_object() || !body.contains("value") || !body["value"].is_string())
+            throw ApiError(ErrCode::Unprocessable, "validation", "value (string) is required");
+        const std::string value = body["value"].get<std::string>();
+        // An empty value is not a credential, and storing one would leave a
+        // name in `ctx.env` holding "" - which a script reads as present but
+        // broken. DELETE is how a secret goes away.
+        if (value.empty())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "value cannot be empty - DELETE the secret to remove it");
+        if (value.size() > kMaxSecretValueBytes)
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "value exceeds " + std::to_string(kMaxSecretValueBytes) + " bytes");
+
+        ProjectSecretStore store(d->db);
+        // The ceiling applies to NEW names only, so an existing secret can
+        // always be rotated even if the limit was lowered under it.
+        const bool isNew = !store.get(project, name).has_value();
+        if (isNew && store.list(project).size() >= kMaxSecretsPerProject)
+            throw ApiError(ErrCode::Unprocessable, "secret_limit",
+                           "project already holds the maximum of " +
+                               std::to_string(kMaxSecretsPerProject) + " secrets");
+
+        bool created = false;
+        ProjectSecret stored = store.put(project, name, value, created);
+        // 201 on a first write, 200 on a rotation, and never the value back -
+        // the caller just sent it, and an echo would put it in every proxy log
+        // between here and them.
+        sendJson(res, created ? 201 : 200, stored.summaryJson());
+    });
+
+    svr.Delete(R"(/api/v1/projects/([^/]+)/secrets/([^/]+))",
+               [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireAdmin(requireKey(*d, req));
+        requireExistingProject(d, project);
+        const std::string name = secretNameParam(req);
+
+        ProjectSecretStore store(d->db);
+        if (!store.remove(project, name))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such secret");
+        sendJson(res, 200, {{"deleted", name}, {"project", project}});
+    });
+}
+
+} // namespace svapi

+ 78 - 1
src/handlers/project_settings.cpp

@@ -45,6 +45,19 @@ nlohmann::json viewJson(const Settings& global, const ProjectSettings* p) {
               {"openai_api_key_set", p && !p->openaiApiKey.empty()}}}};
 }
 
+/// The function-budget view. Separate from the embedding view because the two
+/// routes have different authority: embeddings are project-manage, this is
+/// admin-only, and mixing them into one document would mean a project manager
+/// reading a field he cannot set - or, worse, a later edit letting him set it.
+nlohmann::json budgetJson(const ProjectSettings* p) {
+    nlohmann::json j;
+    const int64_t maxMs = maxFunctionWallTimeMsFor(p);
+    // Null rather than 0: "no project maximum" and "a maximum of zero" are
+    // different answers, and 0 renders as the second one.
+    j["max_wall_time_ms"] = maxMs > 0 ? nlohmann::json(maxMs) : nlohmann::json(nullptr);
+    return j;
+}
+
 }  // namespace
 
 void registerProjectSettingsRoutes(ApiServer& s) {
@@ -97,11 +110,75 @@ void registerProjectSettingsRoutes(ApiServer& s) {
         sendJson(res, 200, viewJson(*global, proj.get()));
     });
 
+    // The project's function wall-time maximum. ADMIN ONLY, deliberately: it is
+    // the one thing standing between one tenant's `timeoutMs: 120000` and every
+    // other tenant's share of the runner pool, so the party it constrains must
+    // not be the party who sets it.
+    svr.Get(R"(/api/v1/projects/([^/]+)/settings/functions)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireAdmin(requireKey(*d, req));
+        auto proj = d->settings.projectSnapshot(project);
+        sendJson(res, 200, budgetJson(proj.get()));
+    });
+
+    svr.Put(R"(/api/v1/projects/([^/]+)/settings/functions)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        std::string project = req.matches[1];
+        requireAdmin(requireKey(*d, req));
+        auto body = bodyJson(req);
+
+        auto current = d->settings.projectSnapshot(project);
+        ProjectSettings updated = current ? *current : ProjectSettings{};
+        updated.project = project;
+
+        if (body.contains("max_wall_time_ms")) {
+            const nlohmann::json& v = body["max_wall_time_ms"];
+            // null clears the cap, the same "inherit again" convention the
+            // embedding overrides use.
+            if (v.is_null()) updated.maxFunctionWallTimeMs.reset();
+            else if (!v.is_number_integer() || v.get<long long>() <= 0)
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "max_wall_time_ms must be a positive integer, or null to "
+                               "inherit the runner's ceiling");
+            else updated.maxFunctionWallTimeMs = v.get<int64_t>();
+        }
+
+        if (!updated.hasAnyOverrides()) d->settings.removeProject(project);
+        else if (!d->settings.saveProject(updated))
+            throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");
+
+        auto proj = d->settings.projectSnapshot(project);
+        sendJson(res, 200, budgetJson(proj.get()));
+    });
+
     svr.Delete(R"(/api/v1/projects/([^/]+)/settings/embeddings)",
                [d](const httplib::Request& req, httplib::Response& res) {
         std::string project = req.matches[1];
         requireProjectManage(requireKey(*d, req), project);
-        bool had = d->settings.removeProject(project);
+
+        // Clears the EMBEDDING fields only. This used to call removeProject(),
+        // which deletes the whole project settings document - and that document
+        // now also holds default_function_policy and max_function_wall_time_ms.
+        // So "revert my embedding override" silently dropped an admin's
+        // function policy and wall-time cap, a destructive side effect nothing
+        // in the route's name or response hinted at.
+        auto current = d->settings.projectSnapshot(project);
+        if (!current) {
+            sendJson(res, 200, {{"reverted", project}, {"had_overrides", false}});
+            return;
+        }
+        const bool had = current->hasEmbeddingOverrides();
+        ProjectSettings updated = *current;
+        updated.openaiApiBase.clear();
+        updated.openaiApiKey.clear();
+        updated.defaultEmbeddingModel.clear();
+        // Only now is dropping the document right: nothing else is stored in it.
+        if (!updated.hasAnyOverrides()) {
+            d->settings.removeProject(project);
+        } else if (!d->settings.saveProject(updated)) {
+            throw ApiError(ErrCode::Unavailable, "db_error", "could not save project settings");
+        }
         sendJson(res, 200, {{"reverted", project}, {"had_overrides", had}});
     });
 }

+ 6 - 0
src/handlers/projects.cpp

@@ -2,6 +2,7 @@
 #include "db_gateway.hpp"
 #include "errors.hpp"
 #include "json_http.hpp"
+#include "project_secret_store.hpp"
 #include "server.hpp"
 #include <algorithm>
 namespace svapi {
@@ -44,6 +45,11 @@ void registerProjectRoutes(ApiServer& s) {
         for (const auto& m : d->registry.list(project))
             d->db.client().dropCollection(qualify(project, m.name));
         d->db.client().dropCollection(qualify(project, "vectorapi_collections"));
+        // The project's function secrets go with it. dropProject does not
+        // physically purge collection data, so without this a recycled project
+        // name would inherit the previous tenant's live credentials and hand
+        // them to the new tenant's functions as ctx.env.
+        ProjectSecretStore(d->db).dropAll(project);
         if (!d->db.dropProject(project)) throw ApiError(ErrCode::Unavailable, "db_error", "drop failed");
         sendJson(res, 200, {{"deleted", project}});
     });

+ 46 - 0
src/main.cpp

@@ -1,6 +1,10 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
 #include "config.hpp"
+#include "function_events.hpp"
+#include "function_jobs.hpp"
+#include "function_scheduler.hpp"
+#include "project_secret_store.hpp"
 #include <memory>
 #include "db_gateway.hpp"
 #include "key_store.hpp"
@@ -105,12 +109,49 @@ int main(int argc, char** argv) {
         spdlog::info("no function runners configured - function routes will answer 503");
     }
 
+    // The queue has to exist and be re-opened before the watcher subscribes or
+    // the scheduler ticks, or their first pass finds nothing and quietly does
+    // nothing for a whole refresh interval.
+    svapi::FunctionJobQueue jobQueue(db);
+    jobQueue.ensure();
+
+    // Secrets are per project and created on demand; ensuring them here only
+    // re-opens what already exists so the runner's reads see it after a restart.
+    svapi::ProjectSecretStore secrets(db);
+    for (const std::string& project : projects) secrets.ensure(project);
+
+    // Started only with runners configured: a queue nobody drains is worse than
+    // no queue, because the jobs look like work in progress forever.
+    std::unique_ptr<svapi::FunctionScheduler> scheduler;
+    std::unique_ptr<svapi::FunctionEventWatcher> events;
+
     svapi::SessionStore sessions(std::chrono::minutes(settings.snapshot()->sessionTtlMinutes));
 
     svapi::ServerDeps deps{db,        settings,     keys,          registry,
                            sessions,  functions,    functionRuns,  runners.get(),
                            cfg.webuiDir, shareDir};
     svapi::ApiServer server(std::move(deps));
+    if (runners && cfg.schedulerEnabled) {
+        svapi::FunctionSchedulerOptions so;
+        so.tickIntervalSec   = cfg.schedulerTickSec;
+        so.reclaimIntervalSec = cfg.reclaimIntervalSec;
+        so.claimTimeoutSec   = cfg.claimTimeoutSec;
+        so.maxAttempts       = cfg.jobMaxAttempts;
+        scheduler = std::make_unique<svapi::FunctionScheduler>(db, functions, jobQueue, so);
+        scheduler->start();
+        spdlog::info("cron scheduler started (tick {}s, reclaim {}s)", so.tickIntervalSec,
+                     so.reclaimIntervalSec);
+    }
+    if (runners && cfg.eventsEnabled) {
+        svapi::FunctionEventWatcherOptions eo;
+        eo.maxDepth          = cfg.eventsMaxDepth;
+        eo.refreshIntervalSec = cfg.eventsRefreshSec;
+        eo.maxPendingEvents  = cfg.eventsMaxPending;
+        events = std::make_unique<svapi::FunctionEventWatcher>(db, functions, jobQueue, eo);
+        events->start();
+        spdlog::info("database event watcher started (max trigger depth {})", eo.maxDepth);
+    }
+
     server.registerRoutes();
 
     std::thread http([&] {
@@ -120,6 +161,11 @@ int main(int argc, char** argv) {
     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");
+    // Background threads first, while the database is still reachable: the
+    // scheduler and the watcher both write to the queue, and a thread still
+    // running when the gateway is destroyed is a use-after-free. Both join.
+    if (events) events->stop();
+    if (scheduler) scheduler->stop();
     server.stop();
     if (http.joinable()) http.join();
     return 0;

+ 80 - 0
src/project_secret_store.cpp

@@ -0,0 +1,80 @@
+#include "project_secret_store.hpp"
+#include <ctime>
+
+namespace svapi {
+namespace {
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+} // namespace
+
+ProjectSecretStore::ProjectSecretStore(DbGateway& db) : db_(db) {}
+
+void ProjectSecretStore::ensure(const std::string& project) {
+    const std::string c = collectionFor(project);
+    // Encrypted at rest, like the settings collection that holds the global
+    // provider key. The flag is fixed at creation, so it has to be right the
+    // first time - there is no later upgrade for a collection created plain.
+    if (!db_.client().getCollectionInfo(c).has_value())
+        db_.client().createCollection(c, 0, /*encrypted*/ true, 0, 0);
+}
+
+std::optional<ProjectSecret> ProjectSecretStore::get(const std::string& project,
+                                                     const std::string& name) {
+    ensure(project);
+    if (auto doc = db_.client().get(collectionFor(project), name))
+        return ProjectSecret::fromJson(*doc);
+    return std::nullopt;
+}
+
+std::vector<ProjectSecret> ProjectSecretStore::list(const std::string& project) {
+    ensure(project);
+    std::vector<ProjectSecret> out;
+    smartbotic::database::Client::QueryOptions opts;
+    // One more than the ceiling: a project that somehow holds more (a limit
+    // lowered later) still lists what is there rather than hiding rows.
+    opts.limit = static_cast<uint32_t>(kMaxSecretsPerProject) + 1;
+    for (const auto& doc : db_.client().find(collectionFor(project), opts))
+        out.push_back(ProjectSecret::fromJson(doc));
+    return out;
+}
+
+std::map<std::string, std::string> ProjectSecretStore::valuesFor(const std::string& project) {
+    std::map<std::string, std::string> out;
+    for (const ProjectSecret& s : list(project)) {
+        // A row whose name failed the rule cannot have come through the API;
+        // it would be a hand-written document, and it is skipped rather than
+        // injected into `ctx.env` under whatever spelling it carries.
+        if (!validSecretName(s.name)) continue;
+        out[s.name] = s.value;
+    }
+    return out;
+}
+
+ProjectSecret ProjectSecretStore::put(const std::string& project, const std::string& name,
+                                      const std::string& value, bool& created) {
+    ensure(project);
+    const std::optional<ProjectSecret> existing = get(project, name);
+    created = !existing.has_value();
+
+    ProjectSecret row;
+    row.name      = name;
+    row.value     = value;
+    // A rotation keeps the original created_at: the pair of timestamps is how
+    // an operator tells "set once at install" from "rotated this morning".
+    row.createdAt = existing && existing->createdAt != 0 ? existing->createdAt : nowSec();
+    row.updatedAt = nowSec();
+    db_.client().upsert(collectionFor(project), row.toJson(), name);
+    return row;
+}
+
+bool ProjectSecretStore::remove(const std::string& project, const std::string& name) {
+    ensure(project);
+    const std::string c = collectionFor(project);
+    if (!db_.client().exists(c, name)) return false;
+    return db_.client().remove(c, name);
+}
+
+void ProjectSecretStore::dropAll(const std::string& project) {
+    db_.client().dropCollection(collectionFor(project));
+}
+
+} // namespace svapi

+ 64 - 0
src/project_secret_store.hpp

@@ -0,0 +1,64 @@
+#pragma once
+#include "db_gateway.hpp"
+#include "project_secrets.hpp"
+#include <map>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// The collection name, unqualified. Service-prefixed (the `vectorapi_` prefix
+/// is reserved against collection-create) and with NO leading underscore,
+/// because an `_`-prefixed collection misroutes when project-qualified.
+constexpr const char* kProjectSecretsCollection = "vectorapi_secrets";
+
+/// DB-backed per-project secret store, used by the admin routes to write and by
+/// the runner to read. Stateless apart from the gateway reference, so it can be
+/// constructed where it is needed - there is deliberately no snapshot cache: a
+/// cached secret is a rotated credential that keeps working, and every read
+/// here already sits next to the registry read a run performs anyway.
+class ProjectSecretStore {
+public:
+    explicit ProjectSecretStore(DbGateway& db);
+
+    /// Ensure the project's secret collection exists, ENCRYPTED, and is open in
+    /// this process. The database only surfaces a collection through find()
+    /// once it has been opened here, so a read path calls this too - the same
+    /// reason CollectionRegistry::bootstrap exists.
+    void ensure(const std::string& project);
+
+    std::optional<ProjectSecret> get(const std::string& project, const std::string& name);
+
+    /// Every secret of one project, values included. Only two callers may want
+    /// this: the runner building `ctx.env`, and names() below.
+    std::vector<ProjectSecret> list(const std::string& project);
+
+    /// Name -> value for one project, for `ctx.env`. Throws on a database
+    /// failure rather than returning an empty map: a function that silently
+    /// runs without its credentials fails somewhere far away from the cause.
+    std::map<std::string, std::string> valuesFor(const std::string& project);
+
+    /// Store or replace one value. `name` must already have passed
+    /// validSecretName(). Returns the stored row (timestamps filled in);
+    /// `created` says whether the secret was new.
+    ProjectSecret put(const std::string& project, const std::string& name,
+                      const std::string& value, bool& created);
+
+    /// Returns false when the project had no such secret.
+    bool remove(const std::string& project, const std::string& name);
+
+    /// Drop the whole collection - for project deletion. A recycled project
+    /// name must never inherit the previous tenant's credentials, and
+    /// dropProject does not physically purge collection data.
+    void dropAll(const std::string& project);
+
+    static std::string collectionFor(const std::string& project) {
+        return qualify(project, kProjectSecretsCollection);
+    }
+
+private:
+    DbGateway& db_;
+};
+
+} // namespace svapi

+ 28 - 0
src/project_secrets.cpp

@@ -0,0 +1,28 @@
+#include "project_secrets.hpp"
+
+namespace svapi {
+
+ProjectSecret ProjectSecret::fromJson(const nlohmann::json& j) {
+    ProjectSecret s;
+    s.name      = j.value("name", "");
+    s.value     = j.value("value", "");
+    s.createdAt = j.value("created_at", 0ull);
+    s.updatedAt = j.value("updated_at", 0ull);
+    return s;
+}
+
+nlohmann::json ProjectSecret::toJson() const {
+    return {{"name", name}, {"value", value},
+            {"created_at", createdAt}, {"updated_at", updatedAt}};
+}
+
+nlohmann::json ProjectSecret::summaryJson() const {
+    // `set` is a field of its own rather than implied by presence, so a client
+    // listing secrets sees the shape the settings endpoints already use for
+    // openai_api_key: a name and a boolean, never a masked value that someone
+    // would be tempted to parse.
+    return {{"name", name}, {"set", !value.empty()},
+            {"created_at", createdAt}, {"updated_at", updatedAt}};
+}
+
+} // namespace svapi

+ 96 - 0
src/project_secrets.hpp

@@ -0,0 +1,96 @@
+#pragma once
+#include <cstddef>
+#include <cstdint>
+#include <nlohmann/json.hpp>
+#include <string>
+
+namespace svapi {
+
+/// Per-project function secrets: the values a function reads as `ctx.env.<NAME>`.
+///
+/// This header is the PURE half - the name rule, the limits and the stored
+/// shape. It deliberately includes nothing but nlohmann/json, so the rules can
+/// be unit-tested, and so the shape can be linked without a database.
+///
+/// Storage is one document per secret in `<project>:vectorapi_secrets`, NOT a
+/// field of the per-project settings document:
+///   - the settings document is loaded wholesale into one in-memory map of
+///     every project (SettingsStore::reloadProjectsFromDb) and handed out by
+///     projectSnapshot() to embedding, dispatch and view code; a credential has
+///     no business travelling through code whose job is to serialize settings;
+///   - that document is readable, in view form, by a non-admin project-manage
+///     caller, while a secret value must never be readable by anyone;
+///   - the secrets collection is project-QUALIFIED, so its name is derived from
+///     the project the caller was authorized for. Reading another tenant's
+///     secrets is not forbidden by a check, it is unreachable;
+///   - one document per secret means setting SLACK_TOKEN cannot clobber a
+///     concurrent write of BOT_TOKEN, which a read-modify-write of a single
+///     document would.
+/// The collection is never added to the collection registry, which is what
+/// keeps it off the documents API and out of `ctx.collections`: both answer 404
+/// for a collection with no registry row, so not even a function policy that
+/// grants every collection can reach it.
+
+/// Longest accepted NAME. Generous for an environment-variable identifier and
+/// short enough that the whole set stays a readable object in a run log.
+constexpr std::size_t kMaxSecretNameLength = 64;
+
+/// Longest accepted value, in bytes. Covers tokens, signing keys and a PEM
+/// private key, while keeping one tenant from using the secret store as a
+/// document store that is copied into every run's context.
+constexpr std::size_t kMaxSecretValueBytes = 8192;
+
+/// Most secrets one project may hold. Every one of them is materialized into
+/// `ctx.env` on every run, so the ceiling is a per-run cost, not just a quota.
+constexpr std::size_t kMaxSecretsPerProject = 64;
+
+/// True when `name` is a safe environment-variable-style identifier:
+/// `[A-Z_][A-Z0-9_]*`, at most kMaxSecretNameLength characters.
+///
+/// Upper case only, and no '-', '.' or ':', because the name shares one
+/// namespace with the host variables `SVAPI_FN_<project>__<NAME>` that an
+/// operator sets in the runner's environment. Restricting the charset to what a
+/// POSIX environment variable can carry means every stored name is also
+/// expressible as a host variable, so the two sources can never hold "the same"
+/// secret under two spellings that differ only in case or in a character the
+/// environment cannot represent - and the merge can then compare names exactly,
+/// with no normalisation step to get wrong. ':' is additionally the qualify()
+/// separator and has no business in a caller-supplied identifier.
+///
+/// Inline on purpose: the runner's `ctx.env` assembly applies the same rule to
+/// what it reads back out of storage, and a header-only rule means that second
+/// use needs no link dependency and cannot drift into a second spelling.
+inline bool validSecretName(const std::string& name) {
+    if (name.empty() || name.size() > kMaxSecretNameLength) return false;
+    // A leading digit is not an identifier anywhere this name is used, so it is
+    // refused rather than quietly accepted into `ctx.env`, where a script could
+    // then only reach it through bracket syntax.
+    if (name[0] >= '0' && name[0] <= '9') return false;
+    for (const char c : name) {
+        const bool ok = (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
+        if (!ok) return false;
+    }
+    return true;
+}
+
+/// One stored secret. `name` travels in the body as well as being the document
+/// id, because the database client strips a top-level `id` from stored bodies
+/// (the same reason an API key stores `key_id`).
+struct ProjectSecret {
+    std::string name;
+    std::string value;
+    uint64_t createdAt = 0;
+    uint64_t updatedAt = 0;
+
+    static ProjectSecret fromJson(const nlohmann::json& j);
+
+    /// The stored form. The only representation that ever carries the value.
+    nlohmann::json toJson() const;
+
+    /// The API form: the name, whether a value is set, and the timestamps.
+    /// Never the value, and never its length - a GET of a secret exists to tell
+    /// an author which names their code may read, nothing more.
+    nlohmann::json summaryJson() const;
+};
+
+} // namespace svapi

+ 13 - 0
src/project_settings.cpp

@@ -17,6 +17,12 @@ ProjectSettings ProjectSettings::fromJson(const nlohmann::json& j) {
     // survives a change to the built-in default.
     if (j.contains("default_function_policy") && j.at("default_function_policy").is_object())
         p.defaultFunctionPolicy = KeyScope::fromJson(j.at("default_function_policy"));
+    // Same absent-versus-present distinction, and the same reason: a stored
+    // value survives a change to the runner's default ceiling, an absent key
+    // follows it.
+    if (j.contains("max_function_wall_time_ms") &&
+        j.at("max_function_wall_time_ms").is_number_integer())
+        p.maxFunctionWallTimeMs = j.at("max_function_wall_time_ms").get<int64_t>();
     return p;
 }
 
@@ -28,6 +34,7 @@ nlohmann::json ProjectSettings::toJson() const {
     // Written only when set, so round-tripping a project that never configured
     // one does not quietly pin today's built-in default into storage.
     if (defaultFunctionPolicy) j["default_function_policy"] = defaultFunctionPolicy->toJson();
+    if (maxFunctionWallTimeMs) j["max_function_wall_time_ms"] = *maxFunctionWallTimeMs;
     return j;
 }
 
@@ -50,4 +57,10 @@ KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj) {
     return builtinDefaultFunctionPolicy();
 }
 
+int64_t maxFunctionWallTimeMsFor(const ProjectSettings* proj) {
+    if (proj && proj->maxFunctionWallTimeMs && *proj->maxFunctionWallTimeMs > 0)
+        return *proj->maxFunctionWallTimeMs;
+    return 0;
+}
+
 } // namespace svapi

+ 22 - 1
src/project_settings.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include "apikey.hpp"
 #include <nlohmann/json.hpp>
+#include <cstdint>
 #include <optional>
 #include <string>
 
@@ -31,6 +32,16 @@ struct ProjectSettings {
     /// retroactively widens or narrows anything already deployed.
     std::optional<KeyScope> defaultFunctionPolicy;
 
+    /// The longest wall time any of this project's functions may be granted,
+    /// in milliseconds. Unset means "whatever the runner's ceiling allows".
+    ///
+    /// Admin-settable and narrowing only: it cannot raise a ceiling, only cut a
+    /// project's scripts below one. It exists because the job ceiling is minutes
+    /// long, and without a per-project cap one tenant's `timeoutMs: 120000`
+    /// holds a pooled runtime - a shared resource - for two minutes at a time,
+    /// which is a denial of service against every other project on the runner.
+    std::optional<int64_t> maxFunctionWallTimeMs;
+
     /// True when at least one EMBEDDING field overrides the global value.
     bool hasEmbeddingOverrides() const {
         return !openaiApiBase.empty() || !openaiApiKey.empty() || !defaultEmbeddingModel.empty();
@@ -41,7 +52,8 @@ struct ProjectSettings {
     /// keying the delete on the embedding fields alone would silently drop a
     /// function policy the moment someone cleared an embedding override.
     bool hasAnyOverrides() const {
-        return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value();
+        return hasEmbeddingOverrides() || defaultFunctionPolicy.has_value() ||
+               maxFunctionWallTimeMs.has_value();
     }
 
     /// A project base URL must carry its own API key, otherwise the global
@@ -76,4 +88,13 @@ ResolvedEmbedding resolveEmbedding(const Settings& global, const ProjectSettings
 /// null when the project has nothing stored.
 KeyScope defaultFunctionPolicyFor(const ProjectSettings* proj);
 
+/// The project's wall-time maximum in milliseconds, or 0 when it has none.
+///
+/// 0 is "no project cap", not "no time": the runner reads it that way and falls
+/// back to its own ceiling. `proj` may be null when the project has nothing
+/// stored. A stored value <= 0 is treated as unset rather than as a project
+/// nobody can run a function in, because that is what a fat-fingered 0 means
+/// and the other reading takes a release to notice.
+int64_t maxFunctionWallTimeMsFor(const ProjectSettings* proj);
+
 } // namespace svapi

+ 11 - 6
src/runner_client.hpp

@@ -50,12 +50,17 @@ public:
     struct Options {
         std::vector<std::string> endpoints;  // "host:port" or full base URLs
         uint32_t connectTimeoutSec = 2;
-        /// MUST exceed the runner's `max_wall_time_ms`, or our read times out
-        /// before the runner can report its own timeout and the caller gets a
-        /// 503 ("no runner available") instead of the truthful 504. The
-        /// defaults here and in runner/config/runner.json satisfy that with
-        /// room to spare (30 s against 2 s); raising the runner's ceiling means
-        /// raising this too.
+        /// MUST exceed the runner's HTTP wall ceiling
+        /// (`runtime.max_http_wall_time_ms`), or our read times out before the
+        /// runner can report its own timeout and the caller gets a 503 ("no
+        /// runner available") instead of the truthful 504. The defaults here
+        /// and in runner/config/runner.json satisfy that with room to spare
+        /// (30 s against 2 s); raising the runner's HTTP ceiling means raising
+        /// this too.
+        ///
+        /// The runner's JOB ceiling is deliberately NOT bound by this number
+        /// and is far above it: a job run is claimed from the queue inside the
+        /// runner process, so no socket of ours is waiting on it.
         uint32_t readTimeoutSec = 30;
         /// How long a failed runner is skipped before being retried.
         uint32_t unhealthyBackoffSec = 10;

+ 1 - 0
src/server.cpp

@@ -168,6 +168,7 @@ void ApiServer::registerRoutes() {
     registerStatsRoutes(*this);
     registerSettingsRoutes(*this);
     registerProjectSettingsRoutes(*this);
+    registerProjectSecretRoutes(*this);
     registerRelationRoutes(*this);
     registerFunctionRoutes(*this);
     // LAST. Function dispatch owns /fn/* , and registering it after the

+ 1 - 0
src/server.hpp

@@ -89,6 +89,7 @@ void registerVectorRoutes(ApiServer&);
 void registerStatsRoutes(ApiServer&);
 void registerSettingsRoutes(ApiServer&);
 void registerProjectSettingsRoutes(ApiServer&);
+void registerProjectSecretRoutes(ApiServer&);
 void registerRelationRoutes(ApiServer&);
 void registerFunctionRoutes(ApiServer&);
 // Registered LAST: it claims /fn/* , and a function route must never shadow

+ 1 - 1
src/settings.cpp

@@ -21,7 +21,7 @@ Settings Settings::fromJson(const nlohmann::json& j) {
     s.embeddingClientPoolSize    = j.value("embedding_client_pool_size",  s.embeddingClientPoolSize);
     if (j.contains("function_egress_blocked_cidrs") && j["function_egress_blocked_cidrs"].is_array()) {
         // Bind before iterating: a range-for over a temporary subobject of a
-        // parsed document dangles (CLAUDE.md).
+        // parsed document dangles.
         const nlohmann::json& cidrs = j["function_egress_blocked_cidrs"];
         for (const auto& c : cidrs)
             if (c.is_string() && !c.get<std::string>().empty())

+ 1 - 2
src/vector_search.cpp

@@ -14,8 +14,7 @@ std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
     opts.filters = filters;
     opts.limit   = kVectorFilterScanCap;
     std::unordered_set<std::string> allowed;
-    // Bind the result before iterating: a range-for over a temporary dangles
-    // (CLAUDE.md).
+    // Bind the result before iterating: a range-for over a temporary dangles.
     const std::vector<nlohmann::json> matched = client.find(coll, opts);
     for (const auto& doc : matched) {
         const std::string id = doc.value("_id", "");

+ 1 - 1
src/vector_search.hpp

@@ -16,7 +16,7 @@ constexpr uint32_t kVectorFilterScanCap = 10000;
 /// ONE implementation on purpose. This is reached from the HTTP route
 /// (`handlers/vectors.cpp`) and from a function's `ctx.collections(...).search()`
 /// in the runner, and the two must not drift: the project guarantees that a
-/// filter means the same thing wherever it is written (CLAUDE.md, "Filters").
+/// filter means the same thing wherever it is written.
 /// When this lived in the route's lambda, the runner had to copy it, cap and
 /// loop included.
 ///

+ 68 - 1
tests/CMakeLists.txt

@@ -88,7 +88,9 @@ gtest_discover_tests(test_principal)
 # (see CLAUDE.md, "The Void dev host can no longer build the C++ natively").
 add_executable(test_functions_descriptor
     test_functions_descriptor.cpp
-    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp)
+    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/cron.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/timezone.cpp)
 target_include_directories(test_functions_descriptor PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_functions_descriptor PRIVATE
     nlohmann_json::nlohmann_json GTest::gtest_main)
@@ -138,3 +140,68 @@ target_link_libraries(test_runner_client PRIVATE
     httplib::httplib nlohmann_json::nlohmann_json spdlog::spdlog
     OpenSSL::SSL OpenSSL::Crypto GTest::gtest_main)
 gtest_discover_tests(test_runner_client)
+
+# The cron engine: pure, so it builds and runs on the dev host. It is also what
+# descriptor.cpp validates schedules with, so a schedule that stores and a
+# schedule that fires cannot disagree.
+add_executable(test_functions_cron
+    test_functions_cron.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/cron.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/timezone.cpp)
+target_include_directories(test_functions_cron PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_functions_cron PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_functions_cron)
+
+# The IANA time zone seam. Pure apart from the host tz database, which is a
+# declared runtime dependency of the packages.
+add_executable(test_functions_timezone
+    test_functions_timezone.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/timezone.cpp)
+target_include_directories(test_functions_timezone PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_functions_timezone PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_functions_timezone)
+
+# Scheduler and event-watcher DECISIONS: pure, so no database client.
+add_executable(test_function_scheduler
+    test_function_scheduler.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/cron.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/timezone.cpp)
+target_include_directories(test_function_scheduler PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_function_scheduler PRIVATE
+    nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_function_scheduler)
+
+# The job queue against a link-time fake database: this target defines the few
+# Client members the queue calls, including the version read and the
+# compare-and-set that make claiming atomic, so it must NOT link vectorapi_core.
+add_executable(test_function_jobs
+    test_function_jobs.cpp
+    ${CMAKE_SOURCE_DIR}/src/function_jobs.cpp
+    ${CMAKE_SOURCE_DIR}/src/apikey.cpp)
+target_include_directories(test_function_jobs PRIVATE
+    ${CMAKE_SOURCE_DIR}/src
+    $<TARGET_PROPERTY:smartbotic::db-client,INTERFACE_INCLUDE_DIRECTORIES>)
+target_link_libraries(test_function_jobs PRIVATE
+    nlohmann_json::nlohmann_json OpenSSL::Crypto GTest::gtest_main)
+gtest_discover_tests(test_function_jobs)
+
+# Secret name rules and the API view that must never carry a value.
+add_executable(test_project_secrets
+    test_project_secrets.cpp
+    ${CMAKE_SOURCE_DIR}/src/project_secrets.cpp)
+target_include_directories(test_project_secrets PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_project_secrets PRIVATE nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_project_secrets)
+
+# The secret store, same link-time fake database approach.
+add_executable(test_project_secret_store
+    test_project_secret_store.cpp
+    ${CMAKE_SOURCE_DIR}/src/project_secrets.cpp
+    ${CMAKE_SOURCE_DIR}/src/project_secret_store.cpp)
+target_include_directories(test_project_secret_store PRIVATE
+    ${CMAKE_SOURCE_DIR}/src
+    $<TARGET_PROPERTY:smartbotic::db-client,INTERFACE_INCLUDE_DIRECTORIES>)
+target_link_libraries(test_project_secret_store PRIVATE
+    nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_project_secret_store)

+ 304 - 0
tests/test_api_integration.cpp

@@ -1801,3 +1801,307 @@ TEST_F(ApiFixture, CollectionReportsRelationsEnforced) {
     ASSERT_TRUE(on.has_value());
     EXPECT_TRUE(*on);
 }
+
+// ===== Document version semantics: PUT-as-upsert, ?if_version=, read-back =====
+//
+// These need a live database: every assertion is about what the database
+// actually stores and reports, which is the half a unit test cannot reach.
+
+// A read must carry the version, or ?if_version= has no source for its value.
+TEST_F(ApiFixture, DocumentReadsCarryVersionAndEtag) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","vers"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/vers/documents";
+
+    auto ins = c.Post(docs.c_str(), nlohmann::json{{"name","Alice"}}.dump(), "application/json");
+    ASSERT_EQ(ins->status, 201) << ins->body;
+    const std::string id = nlohmann::json::parse(ins->body)["id"];
+
+    auto got = c.Get((docs + "/" + id).c_str());
+    ASSERT_EQ(got->status, 200) << got->body;
+    const nlohmann::json doc = nlohmann::json::parse(got->body);
+    ASSERT_TRUE(doc.contains("_version")) << got->body;
+    ASSERT_TRUE(doc["_version"].is_number()) << got->body;
+    EXPECT_EQ(doc["_version"].get<uint64_t>(), 1u);
+    EXPECT_EQ(doc["_id"], id);
+    EXPECT_EQ(got->get_header_value("ETag"), "\"1\"");
+
+    // The same metadata must be on every row of a listing, so a filtered view
+    // is a usable starting point for a conditional write.
+    auto list = c.Get((docs + "?filter=name:eq:Alice").c_str());
+    ASSERT_EQ(list->status, 200) << list->body;
+    const nlohmann::json listJson = nlohmann::json::parse(list->body);
+    ASSERT_GE(listJson["count"].get<int>(), 1);
+    const nlohmann::json& row = listJson["documents"][0];
+    ASSERT_TRUE(row.contains("_version")) << list->body;
+    EXPECT_TRUE(row.contains("_id"));
+}
+
+// PUT creates the document when it is absent (the client keys records by an id
+// it receives from elsewhere and cannot know before the first write).
+TEST_F(ApiFixture, PutCreatesThenReplaces) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","upsert"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/upsert/documents/call-abc123";
+
+    auto created = c.Put(one.c_str(), nlohmann::json{{"status","ringing"}}.dump(), "application/json");
+    ASSERT_TRUE(created);
+    ASSERT_EQ(created->status, 201) << created->body;
+    const nlohmann::json cj = nlohmann::json::parse(created->body);
+    EXPECT_EQ(cj["id"], "call-abc123");
+    EXPECT_TRUE(cj["created"].get<bool>());
+    EXPECT_EQ(cj["version"].get<uint64_t>(), 1u);
+    EXPECT_FALSE(created->get_header_value("Location").empty());
+
+    auto got = c.Get(one.c_str());
+    ASSERT_EQ(got->status, 200) << got->body;
+    EXPECT_EQ(nlohmann::json::parse(got->body)["status"], "ringing");
+
+    auto replaced = c.Put(one.c_str(), nlohmann::json{{"state","answered"}}.dump(), "application/json");
+    ASSERT_EQ(replaced->status, 200) << replaced->body;
+    const nlohmann::json rj = nlohmann::json::parse(replaced->body);
+    EXPECT_FALSE(rj["created"].get<bool>());
+    EXPECT_EQ(rj["version"].get<uint64_t>(), 2u);
+
+    auto after = c.Get(one.c_str());
+    ASSERT_EQ(after->status, 200);
+    const nlohmann::json aj = nlohmann::json::parse(after->body);
+    EXPECT_EQ(aj["state"], "answered");
+    EXPECT_EQ(aj["_version"].get<uint64_t>(), 2u);
+    // A replace drops the fields the body omits; PUT is not a merge.
+    EXPECT_FALSE(aj.contains("status"));
+}
+
+// PATCH keeps its 404: merging fields into a document that does not exist has
+// no defined result, and a patch body is not a whole document.
+TEST_F(ApiFixture, PatchOnMissingDocumentStays404) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","nopatch"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/nopatch/documents/ghost";
+    EXPECT_EQ(c.Patch(one.c_str(), nlohmann::json{{"a",1}}.dump(), "application/json")->status, 404);
+    EXPECT_EQ(c.Patch((one + "?if_version=1").c_str(), nlohmann::json{{"a",1}}.dump(),
+                      "application/json")->status, 404);
+    // A conditional PUT never creates either: there is no version to match.
+    auto condPut = c.Put((one + "?if_version=1").c_str(), nlohmann::json{{"a",1}}.dump(),
+                         "application/json");
+    ASSERT_TRUE(condPut);
+    EXPECT_EQ(condPut->status, 404) << condPut->body;
+}
+
+TEST_F(ApiFixture, ConditionalPatchAppliesThenConflicts) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","cond"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/cond/documents";
+    auto ins = c.Post(docs.c_str(), nlohmann::json{{"status","new"},{"keep",true}}.dump(),
+                      "application/json");
+    ASSERT_EQ(ins->status, 201) << ins->body;
+    const std::string one = docs + "/" + nlohmann::json::parse(ins->body)["id"].get<std::string>();
+
+    // At version 1, a patch conditioned on 1 applies and reports 2.
+    auto ok = c.Patch((one + "?if_version=1").c_str(), nlohmann::json{{"status","done"}}.dump(),
+                      "application/json");
+    ASSERT_TRUE(ok);
+    ASSERT_EQ(ok->status, 200) << ok->body;
+    EXPECT_EQ(nlohmann::json::parse(ok->body)["version"].get<uint64_t>(), 2u);
+
+    // The merge is a merge: the untouched field survives, so the conditional
+    // path really does reproduce what a server-side patch does.
+    auto got = c.Get(one.c_str());
+    ASSERT_EQ(got->status, 200);
+    const nlohmann::json doc = nlohmann::json::parse(got->body);
+    EXPECT_EQ(doc["status"], "done");
+    EXPECT_TRUE(doc["keep"].get<bool>());
+    EXPECT_EQ(doc["_version"].get<uint64_t>(), 2u);
+
+    // Replaying the same conditional request must not apply twice.
+    auto stale = c.Patch((one + "?if_version=1").c_str(), nlohmann::json{{"status","again"}}.dump(),
+                         "application/json");
+    ASSERT_TRUE(stale);
+    ASSERT_EQ(stale->status, 409) << stale->body;
+    const nlohmann::json err = nlohmann::json::parse(stale->body);
+    EXPECT_EQ(err["error"]["code"], "version_conflict");
+    EXPECT_EQ(err["error"]["details"]["expected_version"].get<uint64_t>(), 1u);
+    EXPECT_EQ(err["error"]["details"]["current_version"].get<uint64_t>(), 2u);
+    auto unchanged = c.Get(one.c_str());
+    ASSERT_EQ(unchanged->status, 200);
+    EXPECT_EQ(nlohmann::json::parse(unchanged->body)["status"], "done");
+}
+
+TEST_F(ApiFixture, ConditionalPutAppliesThenConflicts) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","condput"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/condput/documents/rec-1";
+    ASSERT_EQ(c.Put(one.c_str(), nlohmann::json{{"n",1}}.dump(), "application/json")->status, 201);
+
+    auto ok = c.Put((one + "?if_version=1").c_str(), nlohmann::json{{"n",2}}.dump(), "application/json");
+    ASSERT_TRUE(ok);
+    ASSERT_EQ(ok->status, 200) << ok->body;
+    EXPECT_EQ(nlohmann::json::parse(ok->body)["version"].get<uint64_t>(), 2u);
+
+    auto stale = c.Put((one + "?if_version=1").c_str(), nlohmann::json{{"n",3}}.dump(), "application/json");
+    ASSERT_TRUE(stale);
+    ASSERT_EQ(stale->status, 409) << stale->body;
+    EXPECT_EQ(nlohmann::json::parse(stale->body)["error"]["code"], "version_conflict");
+    auto after = c.Get(one.c_str());
+    ASSERT_EQ(after->status, 200);
+    EXPECT_EQ(nlohmann::json::parse(after->body)["n"].get<int>(), 2);
+}
+
+TEST_F(ApiFixture, IfVersionValueIsValidated) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","ifv"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/ifv/documents/x";
+    ASSERT_EQ(c.Put(one.c_str(), nlohmann::json{{"a",1}}.dump(), "application/json")->status, 201);
+    for (const char* bad : {"0", "-1", "abc", "", "1.5"}) {
+        const std::string url = one + "?if_version=" + bad;
+        auto p = c.Patch(url.c_str(), nlohmann::json{{"a",2}}.dump(), "application/json");
+        ASSERT_TRUE(p);
+        EXPECT_EQ(p->status, 422) << "if_version=" << bad << " body: " << p->body;
+        EXPECT_EQ(nlohmann::json::parse(p->body)["error"]["code"], "validation");
+    }
+}
+
+// The two things a version-checked patch cannot carry are refused rather than
+// silently dropped: an expiry (the conditional write has no TTL field) and a
+// stored embedding (a whole-document write would remove it).
+TEST_F(ApiFixture, ConditionalPatchRefusesWhatItCannotCarry) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","condttl"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/condttl/documents/t1";
+    ASSERT_EQ(c.Put(one.c_str(), nlohmann::json{{"a",1}}.dump(), "application/json")->status, 201);
+    auto both = c.Patch((one + "?if_version=1&ttl_seconds=60").c_str(),
+                        nlohmann::json{{"a",2}}.dump(), "application/json");
+    ASSERT_TRUE(both);
+    EXPECT_EQ(both->status, 422) << both->body;
+    EXPECT_EQ(nlohmann::json::parse(both->body)["error"]["code"], "conditional_unsupported");
+
+    // A vector collection is no longer refused. The old implementation read the
+    // document, merged here and wrote the WHOLE document back, which dropped
+    // the stored embedding because a read does not hand it back. patchIfVersion
+    // merges server-side, so the vector is untouched and the refusal would now
+    // be blocking a perfectly safe call.
+    ASSERT_EQ(c.Post(base.c_str(),
+        nlohmann::json{{"name","condvec"},{"kind","vector"},{"vector_dimension",mockDim_}}.dump(),
+        "application/json")->status, 201);
+    ASSERT_EQ(c.Post((base + "/condvec/vectors").c_str(),
+        nlohmann::json{{"id","v1"},{"text","hello"},{"metadata",{{"a",1}}}}.dump(),
+        "application/json")->status, 201);
+    auto vec = c.Patch((base + "/condvec/documents/v1?if_version=1").c_str(),
+                       nlohmann::json{{"a",2}}.dump(), "application/json");
+    ASSERT_TRUE(vec);
+    EXPECT_EQ(vec->status, 200) << vec->body;
+}
+
+// A read-modify-write round trip must not store the database's metadata as
+// ordinary fields. Only Client::update() strips them, and the conditional paths
+// do not go through it.
+TEST_F(ApiFixture, WritesIgnoreDatabaseMetadataInTheBody) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","meta"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/meta/documents/m1";
+
+    ASSERT_EQ(c.Put(one.c_str(), nlohmann::json{{"a",1}}.dump(), "application/json")->status, 201);
+    auto first = c.Get(one.c_str());
+    ASSERT_EQ(first->status, 200);
+    nlohmann::json round = nlohmann::json::parse(first->body);
+    EXPECT_EQ(round["_version"].get<uint64_t>(), 1u);
+
+    // Write the document straight back, metadata and all, with one field changed.
+    round["a"] = 2;
+    ASSERT_EQ(c.Put(one.c_str(), round.dump(), "application/json")->status, 200);
+    auto second = c.Get(one.c_str());
+    ASSERT_EQ(second->status, 200);
+    const nlohmann::json after = nlohmann::json::parse(second->body);
+    EXPECT_EQ(after["a"].get<int>(), 2);
+    // The version must be the real one, not the 1 we echoed back.
+    EXPECT_EQ(after["_version"].get<uint64_t>(), 2u);
+    EXPECT_EQ(after["_id"], "m1");
+}
+
+// A duplicate must say WHICH unique index refused the write: a client with
+// several of them cannot act on the slug alone.
+TEST_F(ApiFixture, DuplicateKeyErrorNamesTheField) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","dup"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post((base + "/dup/indexes").c_str(),
+        nlohmann::json{{"field","external_id"},{"unique",true}}.dump(), "application/json")->status, 201);
+    const std::string docs = base + "/dup/documents";
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"external_id","CALL-1"}}.dump(),
+                     "application/json")->status, 201);
+
+    auto clash = c.Post(docs.c_str(), nlohmann::json{{"external_id","CALL-1"}}.dump(),
+                        "application/json");
+    ASSERT_TRUE(clash);
+    ASSERT_EQ(clash->status, 409) << clash->body;
+    const nlohmann::json err = nlohmann::json::parse(clash->body);
+    EXPECT_EQ(err["error"]["code"], "duplicate_values");
+    ASSERT_TRUE(err["error"].contains("details")) << clash->body;
+    EXPECT_EQ(err["error"]["details"]["field"], "external_id");
+    // `values` is an object keyed by field, as the database reports it. It used
+    // to be a single `value` we recovered from the body we had just tried to
+    // write, because the database did not say.
+    EXPECT_EQ(err["error"]["details"]["values"]["external_id"], "CALL-1");
+    EXPECT_TRUE(err["error"]["details"].contains("conflicting_document_id")) << clash->body;
+}
+
+// PUT may create, and creating is an insert: a key whose scope grants update
+// but not insert must not gain the ability to create rows by using PUT.
+TEST_F(ApiFixture, ScopedUpdateOnlyKeyCannotCreateViaPut) {
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(admin().Post(base.c_str(), nlohmann::json{{"name","scopedput"},{"kind","json"}}.dump(),
+                           "application/json")->status, 201);
+    const std::string docs = base + "/scopedput/documents";
+    ASSERT_EQ(admin().Put((docs + "/exists").c_str(), nlohmann::json{{"a",1}}.dump(),
+                          "application/json")->status, 201);
+
+    svapi::ApiKey sk;
+    sk.id = svapi::generateApiKey();
+    sk.key = svapi::generateApiKey();
+    sk.label = "update-only";
+    sk.projects = {project_};
+    sk.admin = false;
+    {
+        svapi::KeyScope sc;
+        svapi::KeyScopeRule rule;
+        rule.collection = "scopedput";
+        rule.ops = {svapi::KeyOp::Update, svapi::KeyOp::Read};
+        sc.rules.push_back(std::move(rule));
+        sk.scope = std::move(sc);
+    }
+    db_->client().upsert(keysColl_, sk.toJson(), sk.id);
+    keys_->bootstrap("");
+    auto scoped = http(sk.key);
+
+    // Replacing an existing document is within the grant.
+    auto replace = scoped.Put((docs + "/exists").c_str(), nlohmann::json{{"a",2}}.dump(),
+                              "application/json");
+    ASSERT_TRUE(replace);
+    EXPECT_EQ(replace->status, 200) << replace->body;
+
+    // Creating a new one is not.
+    auto create = scoped.Put((docs + "/brand-new").c_str(), nlohmann::json{{"a",1}}.dump(),
+                             "application/json");
+    ASSERT_TRUE(create);
+    EXPECT_EQ(create->status, 403) << create->body;
+    EXPECT_EQ(admin().Get((docs + "/brand-new").c_str())->status, 404);
+
+    db_->client().remove(keysColl_, sk.id);
+}

+ 764 - 0
tests/test_function_jobs.cpp

@@ -0,0 +1,764 @@
+// FunctionJobQueue against a fake database.
+//
+// The fake is supplied at LINK time, exactly as tests/test_function_run_log.cpp
+// does it: this file defines the handful of `smartbotic::database::Client`
+// members function_jobs.cpp calls, so the target never links the real client.
+// That is what makes the claiming rule - the one piece of behaviour here worth
+// asserting - testable on a host where libsmartbotic-db-client cannot be linked
+// at all (CLAUDE.md, "The Void dev host can no longer build the C++ natively").
+//
+// Unlike the run-log fake, this one has to model DOCUMENT VERSIONS, because
+// claimNext's whole point is a compare-and-set on them. `g_onVersionRead` is
+// the seam that lets a test play the other runner: it fires after
+// getVersionHistory has decided what to return, so the version the store is
+// holding goes stale under it and the following updateIfVersion fails the way
+// it would in production. Nothing simulates "updateIfVersion returns false" by
+// special-casing it; the race is reproduced, not faked.
+//
+// Every stub ignores `this` and works on the file-static `g_db` below, so no
+// Client or DbGateway object is ever constructed or read; the references handed
+// to the queue point at storage nothing dereferences.
+#include "function_jobs.hpp"
+#include <gtest/gtest.h>
+#include <algorithm>
+#include <functional>
+#include <map>
+#include <string>
+
+using nlohmann::json;
+using Client = smartbotic::database::Client;
+
+namespace {
+
+/// A stored document plus the version the server would be tracking for it.
+struct Row {
+    json body;
+    uint64_t version = 1;
+};
+
+/// collection -> document id -> row.
+std::map<std::string, std::map<std::string, Row>> g_db;
+std::map<std::string, bool> g_created;
+
+/// Fires inside updateIfVersion, before the version is compared. A test uses
+/// it to stand in for another runner winning the row in the window between the
+/// find that gave us a version and the compare-and-set that spends it.
+std::function<void(const std::string& collection, const std::string& id)> g_onVersionRead;
+
+/// Round trips, so a test can pin the cost of one successful claim.
+int g_finds = 0, g_versionReads = 0, g_cas = 0;
+
+void resetDb() {
+    g_db.clear();
+    g_created.clear();
+    g_onVersionRead = nullptr;
+    g_finds = g_versionReads = g_cas = 0;
+}
+
+/// The subset of the filter vocabulary the queue uses. Anything else is a test
+/// bug, not a silently-ignored predicate.
+bool matches(const json& body, const Client::Filter& f) {
+    const json v = body.value(f.field, json());
+    switch (f.op) {
+        case Client::FilterOp::EQ:  return v == f.value;
+        case Client::FilterOp::NE:  return v != f.value;
+        case Client::FilterOp::LTE: return v.is_number() && f.value.is_number() &&
+                                           v.get<double>() <= f.value.get<double>();
+        case Client::FilterOp::LT:  return v.is_number() && f.value.is_number() &&
+                                           v.get<double>() < f.value.get<double>();
+        case Client::FilterOp::GTE: return v.is_number() && f.value.is_number() &&
+                                           v.get<double>() >= f.value.get<double>();
+        case Client::FilterOp::GT:  return v.is_number() && f.value.is_number() &&
+                                           v.get<double>() > f.value.get<double>();
+        case Client::FilterOp::IN: {
+            if (!f.value.is_array()) return false;
+            const json& options = f.value;
+            for (const auto& opt : options)
+                if (v == opt) return true;
+            return false;
+        }
+        default:
+            ADD_FAILURE() << "the queue used an operator this fake does not model: "
+                          << static_cast<int>(f.op);
+            return false;
+    }
+}
+
+}  // namespace
+
+namespace smartbotic::database {
+
+bool Client::createCollection(const std::string& name, uint32_t, bool, uint32_t, uint32_t) {
+    g_created[name] = true;
+    g_db[name];
+    return true;
+}
+
+std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
+    if (!g_created.count(name)) return std::nullopt;
+    CollectionInfo info;
+    info.name = name;
+    info.documentCount = g_db[name].size();
+    return info;
+}
+
+std::pair<std::string, bool> Client::upsert(const std::string& collection, const json& data,
+                                            const std::string& id, uint32_t, const std::string&) {
+    auto& rows = g_db[collection];
+    const bool isNew = rows.count(id) == 0;
+    json body = data;
+    body.erase("id");  // the real client strips a top-level `id` from the body
+    Row& row = rows[id];
+    row.body = std::move(body);
+    row.version = isNew ? 1 : row.version + 1;
+    return {id, isNew};
+}
+
+bool Client::updateIfVersion(const std::string& collection, const std::string& id,
+                             const json& data, uint64_t expectedVersion, const std::string&) {
+    ++g_cas;
+    // Fires BEFORE the compare, which is the window a competing runner writes
+    // in: the claim reads a version from find() and presents it here, so
+    // anything that lands in between is exactly what the CAS exists to catch.
+    if (g_onVersionRead) g_onVersionRead(collection, id);
+    auto& rows = g_db[collection];
+    auto it = rows.find(id);
+    if (it == rows.end()) return false;
+    if (it->second.version != expectedVersion) return false;  // somebody else got here first
+    json body = data;
+    body.erase("id");
+    it->second.body = std::move(body);
+    ++it->second.version;
+    return true;
+}
+
+Client::VersionHistoryResult Client::getVersionHistory(const std::string& collection,
+                                                       const std::string& id, uint32_t, uint32_t) {
+    ++g_versionReads;
+    VersionHistoryResult res;
+    auto& rows = g_db[collection];
+    auto it = rows.find(id);
+    if (it == rows.end()) {
+        res.documentDeleted = true;
+        return res;
+    }
+    res.currentVersion = it->second.version;
+    res.totalCount = 1;
+    return res;
+}
+
+bool Client::remove(const std::string& collection, const std::string& id) {
+    return g_db[collection].erase(id) > 0;
+}
+
+std::optional<json> Client::get(const std::string& collection, const std::string& id) {
+    auto& rows = g_db[collection];
+    auto it = rows.find(id);
+    if (it == rows.end()) return std::nullopt;
+    // Same injected metadata the real client adds on every read.
+    json out = it->second.body;
+    out["_id"] = id;
+    out["_version"] = it->second.version;
+    return out;
+}
+
+std::vector<json> Client::find(const std::string& collection, const QueryOptions& options) {
+    ++g_finds;
+    std::vector<json> rows;
+    for (const auto& [id, row] : g_db[collection]) {
+        bool keep = true;
+        for (const auto& f : options.filters)
+            if (!matches(row.body, f)) { keep = false; break; }
+        if (!keep) continue;
+        // The real client injects `_id` and `_version` into every row it
+        // returns, and the queue claims on that version rather than paying a
+        // separate read for it. A fake that omitted them would be testing a
+        // client that does not exist.
+        json out = row.body;
+        out["_id"] = id;
+        out["_version"] = row.version;
+        rows.push_back(std::move(out));
+    }
+    if (!options.sortField.empty()) {
+        const std::string& key = options.sortField;
+        std::stable_sort(rows.begin(), rows.end(), [&](const json& a, const json& b) {
+            const uint64_t av = a.value(key, 0ull), bv = b.value(key, 0ull);
+            return options.sortDescending ? av > bv : av < bv;
+        });
+    }
+    std::vector<json> page;
+    for (size_t i = options.offset; i < rows.size() && page.size() < options.limit; ++i)
+        page.push_back(rows[i]);
+    return page;
+}
+
+}  // namespace smartbotic::database
+
+namespace svapi {
+
+/// Mirrors db_gateway.cpp. That translation unit cannot be linked here: it
+/// constructs a real Client, whose PIMPL lives in the library this target
+/// exists to avoid.
+std::string qualify(const std::string& project, const std::string& collection) {
+    if (project.empty() || project == "default") return collection;
+    return project + ":" + collection;
+}
+
+Client& DbGateway::client() {
+    alignas(Client) static unsigned char storage[sizeof(void*) * 4];
+    return *reinterpret_cast<Client*>(storage);
+}
+
+}  // namespace svapi
+
+namespace {
+
+/// A DbGateway reference whose object is never touched: every call reaching it
+/// lands in a stub above.
+svapi::DbGateway& fakeGateway() {
+    alignas(svapi::DbGateway) static unsigned char storage[sizeof(void*) * 8];
+    return *reinterpret_cast<svapi::DbGateway*>(storage);
+}
+
+/// The one collection the queue lives in, as the queue qualifies it.
+const char* kColl = "vectorapi_function_jobs";
+
+svapi::FunctionJob job(const std::string& id, const std::string& project,
+                       const std::string& fnId, uint64_t runAfter, uint64_t createdAt) {
+    svapi::FunctionJob j;
+    j.jobId      = id;
+    j.project    = project;
+    j.functionId = fnId;
+    j.trigger    = "cron";
+    j.payload    = {{"scheduled_at", createdAt}};
+    j.runAfter   = runAfter;
+    j.createdAt  = createdAt;
+    return j;
+}
+
+/// Read a row straight out of the fake, bypassing the queue.
+svapi::FunctionJob stored(const std::string& id) {
+    return svapi::FunctionJob::fromJson(g_db[kColl][id].body);
+}
+
+uint64_t nowSec() { return static_cast<uint64_t>(std::time(nullptr)); }
+
+class FunctionJobsTest : public ::testing::Test {
+protected:
+    void SetUp() override { resetDb(); }
+};
+
+// ---------------------------------------------------------------------------
+// Record shape
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, RoundTripsEveryField) {
+    svapi::FunctionJob j = job("j1", "p1", "nightly", 1700000500, 1700000000);
+    j.state     = "claimed";
+    j.claimedBy = "runner-a";
+    j.claimedAt = 1700000600;
+    j.attempts  = 3;
+    j.depth     = 2;
+    j.lastError = "TypeError: x is not a function";
+
+    const svapi::FunctionJob back = svapi::FunctionJob::fromJson(j.toJson());
+    EXPECT_EQ(back.jobId, "j1");
+    EXPECT_EQ(back.project, "p1");
+    EXPECT_EQ(back.functionId, "nightly");
+    EXPECT_EQ(back.trigger, "cron");
+    EXPECT_EQ(back.payload.at("scheduled_at"), 1700000000);
+    EXPECT_EQ(back.state, "claimed");
+    EXPECT_EQ(back.claimedBy, "runner-a");
+    EXPECT_EQ(back.claimedAt, 1700000600u);
+    EXPECT_EQ(back.attempts, 3u);
+    EXPECT_EQ(back.depth, 2u);
+    EXPECT_EQ(back.runAfter, 1700000500u);
+    EXPECT_EQ(back.createdAt, 1700000000u);
+    EXPECT_EQ(back.lastError, "TypeError: x is not a function");
+}
+
+// `job_id`, not `id`: the client strips a top-level `id`, which would leave a
+// stored job with no identity to claim or delete by.
+TEST_F(FunctionJobsTest, StoresItsIdInTheBody) {
+    const json j = svapi::FunctionJob().toJson();
+    EXPECT_TRUE(j.contains("job_id"));
+    EXPECT_FALSE(j.contains("id"));
+}
+
+TEST_F(FunctionJobsTest, AbsentFieldsDoNotInventAJob) {
+    const svapi::FunctionJob j = svapi::FunctionJob::fromJson(json::object());
+    EXPECT_TRUE(j.jobId.empty());
+    EXPECT_EQ(j.attempts, 0u);
+    EXPECT_EQ(j.depth, 0u);
+    EXPECT_TRUE(j.payload.is_object());  // a caller never has to null-check ctx
+}
+
+// ---------------------------------------------------------------------------
+// enqueue
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, EnqueueStampsCreatedAtAndStartsPending) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "nightly", 0, 0);
+    ASSERT_EQ(q.enqueue(j), "j1");
+
+    const svapi::FunctionJob back = stored("j1");
+    EXPECT_GE(back.createdAt, 1700000000u);  // stamped, not left at 0
+    EXPECT_EQ(back.state, "pending");
+    EXPECT_EQ(back.attempts, 0u);
+}
+
+TEST_F(FunctionJobsTest, EnqueueKeepsACallerSuppliedCreatedAt) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    ASSERT_EQ(q.enqueue(job("j1", "p1", "nightly", 0, 1700000000)), "j1");
+    EXPECT_EQ(stored("j1").createdAt, 1700000000u);
+}
+
+TEST_F(FunctionJobsTest, EnqueueMintsAnIdWhenTheCallerHasNone) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    const std::string id = q.enqueue(job("", "p1", "nightly", 0, 0));
+    ASSERT_FALSE(id.empty());
+    EXPECT_EQ(stored(id).jobId, id);  // and the body carries it back
+}
+
+// ---------------------------------------------------------------------------
+// claimNext
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, ClaimNextTakesTheOldestDueJob) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("new", "p1", "fn", 1700000200, 1700000200));
+    q.enqueue(job("old", "p1", "fn", 1700000100, 1700000100));
+
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+    EXPECT_EQ(claimed->jobId, "old");
+    EXPECT_EQ(claimed->state, "claimed");
+    EXPECT_EQ(claimed->claimedBy, "runner-a");
+    EXPECT_GT(claimed->claimedAt, 0u);
+    // And the claim is what is stored, not just what was returned.
+    EXPECT_EQ(stored("old").state, "claimed");
+    EXPECT_EQ(stored("old").claimedBy, "runner-a");
+}
+
+// Candidates are ordered by `run_after`, NOT by `created_at`: "oldest first"
+// means "longest overdue first", so a job deferred to a later time does not
+// jump ahead of work that became due earlier just because it was enqueued
+// first. This is also what keeps a backed-off retry from starving the queue.
+TEST_F(FunctionJobsTest, ClaimNextOrdersByWhenAJobBecameDueNotWhenItWasCreated) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    // Created first, but deliberately deferred.
+    q.enqueue(job("deferred", "p1", "fn", 1700009000, 1700000000));
+    // Created later, and already due by then.
+    q.enqueue(job("due-earlier", "p1", "fn", 1700001000, 1700000500));
+
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+    EXPECT_EQ(claimed->jobId, "due-earlier");
+}
+
+TEST_F(FunctionJobsTest, ClaimNextIncrementsAttemptsAndReportsTheRealCount) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "fn", 0, 1700000000);
+    j.attempts = 2;  // as a reclaim would have left it
+    q.enqueue(j);
+
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+    EXPECT_EQ(claimed->attempts, 3u);
+    EXPECT_EQ(stored("j1").attempts, 3u);
+}
+
+TEST_F(FunctionJobsTest, ClaimNextSkipsAJobThatIsNotDueYet) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("later", "p1", "fn", nowSec() + 3600, 1700000000));
+    EXPECT_FALSE(q.claimNext("runner-a").has_value());
+    EXPECT_EQ(stored("later").state, "pending");
+}
+
+TEST_F(FunctionJobsTest, ClaimNextIgnoresJobsThatAreNotPending) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob done = job("d", "p1", "fn", 0, 1700000000);
+    done.state = "done";
+    q.enqueue(done);
+    svapi::FunctionJob failed = job("f", "p1", "fn", 0, 1700000001);
+    failed.state = "failed";
+    q.enqueue(failed);
+    EXPECT_FALSE(q.claimNext("runner-a").has_value());
+}
+
+// THE RACE. Another runner wins the oldest row in the window between our
+// version read and our compare-and-set; we must not retry that row (it is
+// running right now, elsewhere) and must claim the next candidate instead.
+TEST_F(FunctionJobsTest, ClaimNextMovesOnWhenAnotherRunnerWinsTheRow) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("old", "p1", "fn", 1700000100, 1700000100));
+    q.enqueue(job("next", "p1", "fn", 1700000200, 1700000200));
+
+    g_onVersionRead = [](const std::string& collection, const std::string& id) {
+        if (id != "old") return;
+        Row& row = g_db[collection][id];
+        row.body["state"] = "claimed";
+        row.body["claimed_by"] = "runner-b";
+        ++row.version;  // our caller is now holding a stale version
+    };
+
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+    EXPECT_EQ(claimed->jobId, "next");
+    // The row we lost still belongs to the winner - we did not touch it.
+    EXPECT_EQ(stored("old").claimedBy, "runner-b");
+    EXPECT_EQ(g_cas, 2);  // one failed CAS, one that won; no retry of the loser
+}
+
+TEST_F(FunctionJobsTest, ClaimNextReturnsNullWhenEveryCandidateIsLost) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("a", "p1", "fn", 1700000100, 1700000100));
+    q.enqueue(job("b", "p1", "fn", 1700000200, 1700000200));
+
+    g_onVersionRead = [](const std::string& collection, const std::string& id) {
+        ++g_db[collection][id].version;  // every row is stolen
+    };
+
+    EXPECT_FALSE(q.claimNext("runner-a").has_value());
+    EXPECT_EQ(g_cas, 2);  // tried each candidate exactly once
+}
+
+TEST_F(FunctionJobsTest, ClaimNextReturnsNullOnAnEmptyQueue) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.ensure();
+    EXPECT_FALSE(q.claimNext("runner-a").has_value());
+}
+
+// Two runners racing on the same queue: one job, one winner, and the loser gets
+// nothing rather than a second copy of the same work.
+TEST_F(FunctionJobsTest, TwoRunnersNeverBothGetTheSameJob) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("only", "p1", "fn", 1700000100, 1700000100));
+
+    const auto first = q.claimNext("runner-a");
+    const auto second = q.claimNext("runner-b");
+    ASSERT_TRUE(first.has_value());
+    EXPECT_FALSE(second.has_value());
+    EXPECT_EQ(stored("only").claimedBy, "runner-a");
+    EXPECT_EQ(stored("only").attempts, 1u);
+}
+
+// A claim costs exactly TWO round trips: find the candidates, compare-and-set.
+// It used to cost three, because the version came from a separate history read
+// before anyone noticed the rows already carry `_version`. Worth pinning - a
+// runner does this on every tick, and a third trip here is pure waste.
+TEST_F(FunctionJobsTest, ASuccessfulClaimCostsTwoRoundTrips) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    g_finds = g_versionReads = g_cas = 0;
+    ASSERT_TRUE(q.claimNext("runner-a").has_value());
+    EXPECT_EQ(g_finds, 1);
+    EXPECT_EQ(g_cas, 1);
+    EXPECT_EQ(g_versionReads, 0) << "the version came from the row, not from a history call";
+}
+
+TEST_F(FunctionJobsTest, ClaimNextLooksAtNoMoreThanMaxCandidates) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    for (int i = 0; i < 5; ++i)
+        q.enqueue(job("j" + std::to_string(i), "p1", "fn", 1700000100 + i, 1700000100 + i));
+    g_onVersionRead = [](const std::string& collection, const std::string& id) {
+        ++g_db[collection][id].version;  // lose them all, so every candidate is tried
+    };
+    g_cas = 0;
+    EXPECT_FALSE(q.claimNext("runner-a", 2).has_value());
+    EXPECT_EQ(g_cas, 2);
+}
+
+// ---------------------------------------------------------------------------
+// complete
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, CompleteOkMarksDone) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+
+    EXPECT_TRUE(q.complete(*claimed, true, ""));
+    EXPECT_EQ(stored("j1").state, "done");
+    EXPECT_TRUE(stored("j1").lastError.empty());
+    EXPECT_EQ(stored("j1").attempts, 1u);  // the count survives, for the UI
+}
+
+TEST_F(FunctionJobsTest, CompleteFailWithRetryReturnsItToPendingInTheFuture) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+
+    const uint64_t before = nowSec();
+    EXPECT_TRUE(q.complete(*claimed, false, "boom", 60));
+
+    const svapi::FunctionJob back = stored("j1");
+    EXPECT_EQ(back.state, "pending");
+    EXPECT_EQ(back.lastError, "boom");
+    EXPECT_GE(back.runAfter, before + 60);
+    // No longer claimed: a pending row that still looks claimed would be
+    // reclaimed out from under the backoff.
+    EXPECT_TRUE(back.claimedBy.empty());
+    EXPECT_EQ(back.claimedAt, 0u);
+    // And the backoff is real: claimNext must not pick it up again now.
+    EXPECT_FALSE(q.claimNext("runner-a").has_value());
+}
+
+TEST_F(FunctionJobsTest, CompleteFailWithoutRetryMarksFailed) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+
+    EXPECT_TRUE(q.complete(*claimed, false, "boom", 0));
+    EXPECT_EQ(stored("j1").state, "failed");
+    EXPECT_EQ(stored("j1").lastError, "boom");
+}
+
+TEST_F(FunctionJobsTest, CompleteRefusesAJobWithNoIdentity) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    EXPECT_FALSE(q.complete(svapi::FunctionJob(), true, ""));
+    EXPECT_TRUE(g_db[kColl].empty());  // and writes nothing
+}
+
+// ---------------------------------------------------------------------------
+// reclaimStale
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, ReclaimStaleReturnsAStaleClaimToPending) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "fn", 0, 1700000000);
+    j.state     = "claimed";
+    j.claimedBy = "dead-runner";
+    j.claimedAt = nowSec() - 600;
+    j.attempts  = 1;
+    q.enqueue(j);
+
+    EXPECT_EQ(q.reclaimStale(300, 5), 1u);
+    const svapi::FunctionJob back = stored("j1");
+    EXPECT_EQ(back.state, "pending");
+    EXPECT_TRUE(back.claimedBy.empty());
+    EXPECT_EQ(back.claimedAt, 0u);
+    EXPECT_FALSE(back.lastError.empty());  // why it came back, for an operator
+    // Attempts are NOT rewound: the next claim counts 2, which is what stops a
+    // poisonous job from being retried forever.
+    EXPECT_EQ(back.attempts, 1u);
+    const auto reclaimed = q.claimNext("runner-b");
+    ASSERT_TRUE(reclaimed.has_value());
+    EXPECT_EQ(reclaimed->attempts, 2u);
+}
+
+TEST_F(FunctionJobsTest, ReclaimStaleLeavesAFreshClaimAlone) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "fn", 0, 1700000000);
+    j.state     = "claimed";
+    j.claimedBy = "runner-a";
+    j.claimedAt = nowSec();
+    j.attempts  = 1;
+    q.enqueue(j);
+
+    EXPECT_EQ(q.reclaimStale(300, 5), 0u);
+    EXPECT_EQ(stored("j1").state, "claimed");
+    EXPECT_EQ(stored("j1").claimedBy, "runner-a");
+}
+
+// A job that kills its runner must not kill every runner in turn: once the
+// attempt budget is spent the reclaim fails it instead of handing it on.
+TEST_F(FunctionJobsTest, ReclaimStaleFailsAJobAtMaxAttemptsInsteadOfReclaimingItForever) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "fn", 0, 1700000000);
+    j.state     = "claimed";
+    j.claimedBy = "victim-3";
+    j.claimedAt = nowSec() - 600;
+    j.attempts  = 3;
+    q.enqueue(j);
+
+    EXPECT_EQ(q.reclaimStale(300, 3), 0u);  // not reclaimed - retired
+    const svapi::FunctionJob back = stored("j1");
+    EXPECT_EQ(back.state, "failed");
+    EXPECT_FALSE(back.lastError.empty());
+    // And it is gone from the queue for good: no runner can pick it up again.
+    EXPECT_FALSE(q.claimNext("runner-b").has_value());
+    EXPECT_EQ(q.reclaimStale(300, 3), 0u);
+}
+
+TEST_F(FunctionJobsTest, ReclaimStaleLosesTheRowRatherThanFightingTheRunnerThatHasIt) {
+    // The owning runner finishes in the window between our find and our write.
+    // Its result must stand; we must not resurrect a job that is already done.
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "fn", 0, 1700000000);
+    j.state     = "claimed";
+    j.claimedBy = "slow-runner";
+    j.claimedAt = nowSec() - 600;
+    j.attempts  = 1;
+    q.enqueue(j);
+
+    g_onVersionRead = [](const std::string& collection, const std::string& id) {
+        Row& row = g_db[collection][id];
+        row.body["state"] = "done";
+        ++row.version;
+    };
+
+    EXPECT_EQ(q.reclaimStale(300, 5), 0u);
+    EXPECT_EQ(stored("j1").state, "done");
+}
+
+TEST_F(FunctionJobsTest, ReclaimStaleTreatsAZeroBudgetAsOneAttempt) {
+    // 0 means "keep everything" elsewhere in this codebase; here it must not
+    // mean "retry forever", which is exactly the loop this guard exists to stop.
+    svapi::FunctionJobQueue q(fakeGateway());
+    svapi::FunctionJob j = job("j1", "p1", "fn", 0, 1700000000);
+    j.state     = "claimed";
+    j.claimedAt = nowSec() - 600;
+    j.attempts  = 1;
+    q.enqueue(j);
+
+    EXPECT_EQ(q.reclaimStale(300, 0), 0u);
+    EXPECT_EQ(stored("j1").state, "failed");
+}
+
+// ---------------------------------------------------------------------------
+// hasActive
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, HasActiveSeesBothPendingAndClaimed) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    EXPECT_TRUE(q.hasActive("p1", "fn"));            // pending
+
+    ASSERT_TRUE(q.claimNext("runner-a").has_value());
+    EXPECT_TRUE(q.hasActive("p1", "fn"));            // claimed, still in flight
+}
+
+TEST_F(FunctionJobsTest, HasActiveIsFalseOnceTheJobIsSettled) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+
+    ASSERT_TRUE(q.complete(*claimed, true, ""));
+    EXPECT_FALSE(q.hasActive("p1", "fn"));
+
+    svapi::FunctionJob failed = job("j2", "p1", "fn", 0, 1700000001);
+    failed.state = "failed";
+    q.enqueue(failed);
+    EXPECT_FALSE(q.hasActive("p1", "fn"));
+}
+
+// Single-flight is per function and per project, or one project's backlog would
+// silence another's schedule.
+TEST_F(FunctionJobsTest, HasActiveIsScopedToOneFunctionOfOneProject) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    EXPECT_FALSE(q.hasActive("p1", "other"));
+    EXPECT_FALSE(q.hasActive("p2", "fn"));
+}
+
+// ---------------------------------------------------------------------------
+// list / removeForProject
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, ListIsOldestFirstAndScopedToTheProject) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("b", "p1", "fn", 0, 1700000200));
+    q.enqueue(job("a", "p1", "fn", 0, 1700000100));
+    q.enqueue(job("x", "p2", "fn", 0, 1700000150));
+
+    const auto rows = q.list("p1", 100);
+    ASSERT_EQ(rows.size(), 2u);
+    EXPECT_EQ(rows[0].jobId, "a");
+    EXPECT_EQ(rows[1].jobId, "b");
+}
+
+TEST_F(FunctionJobsTest, ListHonoursItsLimit) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    for (int i = 0; i < 5; ++i)
+        q.enqueue(job("j" + std::to_string(i), "p1", "fn", 0, 1700000100 + i));
+    EXPECT_EQ(q.list("p1", 2).size(), 2u);
+    EXPECT_FALSE(q.list("p1", 0).empty());  // 0 is a default, not "nothing"
+}
+
+TEST_F(FunctionJobsTest, RemoveForProjectDropsOnlyThatProjectsJobs) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("a", "p1", "fn", 0, 1700000100));
+    q.enqueue(job("b", "p1", "fn", 0, 1700000200));
+    q.enqueue(job("x", "p2", "fn", 0, 1700000150));
+
+    EXPECT_EQ(q.removeForProject("p1"), 2u);
+    EXPECT_TRUE(q.list("p1", 100).empty());
+    ASSERT_EQ(q.list("p2", 100).size(), 1u);
+    EXPECT_EQ(q.list("p2", 100)[0].jobId, "x");
+}
+
+TEST_F(FunctionJobsTest, RemoveForProjectOnAnUnknownProjectIsANoOp) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("a", "p1", "fn", 0, 1700000100));
+    EXPECT_EQ(q.removeForProject("nope"), 0u);
+    EXPECT_EQ(q.list("p1", 100).size(), 1u);
+}
+
+// ---------------------------------------------------------------------------
+// ensure
+// ---------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, EnsureCreatesTheQueueCollectionOnceAndIsIdempotent) {
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.ensure();
+    EXPECT_TRUE(g_created.count(kColl));
+    q.enqueue(job("a", "p1", "fn", 0, 1700000100));
+    q.ensure();
+    EXPECT_EQ(g_db[kColl].size(), 1u);  // the second ensure did not wipe it
+}
+
+}  // namespace
+
+// --------------------------------------------------------------------------
+// complete() is a compare-and-set, not a blind write
+// --------------------------------------------------------------------------
+
+TEST_F(FunctionJobsTest, CompleteIsRefusedOnceTheRowHasMovedOn) {
+    // The failure this guards against: runner A's claim goes stale, the sweeper
+    // returns the job to pending, runner B claims and starts executing it - and
+    // then A finally finishes and writes its outcome. A blind upsert would mark
+    // `done` a job B is running right now, or drag it back to `pending` and run
+    // it a third time. A must be told it no longer owns the row.
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    const auto claimedByA = q.claimNext("runner-a");
+    ASSERT_TRUE(claimedByA.has_value());
+
+    // Somebody else writes the row: exactly what a reclaim followed by a second
+    // claim would do, and it is the version bump that matters here.
+    g_db[kColl]["j1"].version += 1;
+    g_db[kColl]["j1"].body["claimed_by"] = "runner-b";
+
+    EXPECT_FALSE(q.complete(*claimedByA, true, ""))
+        << "a superseded runner must not be able to complete the job";
+    EXPECT_EQ(stored("j1").claimedBy, "runner-b") << "runner-a overwrote the new owner";
+    EXPECT_NE(stored("j1").state, "done");
+}
+
+TEST_F(FunctionJobsTest, CompleteRefusesAJobThatNeverCameFromClaimNext) {
+    // version 0 means there is nothing to compare against. Refusing keeps the
+    // unsafe path closed instead of quietly falling back to a blind write.
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    svapi::FunctionJob handMade = job("j1", "p1", "fn", 0, 1700000000);
+    ASSERT_EQ(handMade.version, 0u);
+
+    EXPECT_FALSE(q.complete(handMade, true, ""));
+    EXPECT_EQ(stored("j1").state, "pending") << "a versionless complete still wrote";
+}
+
+TEST_F(FunctionJobsTest, AClaimReportsTheVersionItMustCompleteWith) {
+    // claimNext's CAS moves the row on by one, so the version the caller holds
+    // has to be the post-claim one - otherwise its own claim would supersede it.
+    svapi::FunctionJobQueue q(fakeGateway());
+    q.enqueue(job("j1", "p1", "fn", 0, 1700000000));
+    const auto claimed = q.claimNext("runner-a");
+    ASSERT_TRUE(claimed.has_value());
+    EXPECT_EQ(claimed->version, g_db[kColl]["j1"].version);
+}

+ 1 - 2
tests/test_function_run_log.cpp

@@ -4,8 +4,7 @@
 // `smartbotic::database::Client` members function_run_log.cpp calls, so the
 // target never links the real client. That is what makes the trim rule - the
 // one piece of behaviour here worth asserting - testable on a host where
-// libsmartbotic-db-client cannot be linked at all (CLAUDE.md, "The Void dev
-// host can no longer build the C++ natively").
+// libsmartbotic-db-client cannot be linked at all.
 //
 // Every stub ignores `this` and works on the file-static `g_db` below, so no
 // Client or DbGateway object is ever constructed or read; the references handed

+ 563 - 0
tests/test_function_scheduler.cpp

@@ -0,0 +1,563 @@
+// The decisions behind the cron scheduler and the database-event watcher.
+//
+// Both classes keep every decision in a pure function in their header, so this
+// file exercises the parts that can be silently wrong - a cron that fires twice
+// in a minute, an event that triggers the wrong function, a self-triggering
+// loop that is never refused - WITHOUT a database, a runner or a thread. That
+// is also what lets this target build and run on the dev host, where
+// smartbotic-db-client cannot link (CLAUDE.md, "The Void dev host can no longer
+// build the C++ natively").
+//
+// NOT covered here, and deliberately so: the background threads themselves, the
+// subscribe stream, and anything that needs a live database. Those need the
+// devstack.
+
+#include "function_events.hpp"
+#include "function_scheduler.hpp"
+#include "functions/cron.hpp"
+#include <gtest/gtest.h>
+
+using namespace svapi;
+
+namespace {
+
+/// A cron matcher that fires on whole minutes divisible by `everyMin`. Stands
+/// in for CronExpr::matches, which has its own tests.
+std::function<bool(std::time_t)> everyMinutes(int everyMin) {
+    return [everyMin](std::time_t t) {
+        return (minuteFloor(t) / 60) % everyMin == 0;
+    };
+}
+
+nlohmann::json dbDescriptor(const std::string& id, const std::string& table,
+                            const std::string& event, bool singleFlight = false) {
+    nlohmann::json on{{"id", id}, {"type", "db"}, {"table", table}, {"event", event}};
+    if (singleFlight) on["singleFlight"] = true;
+    return on;
+}
+
+/// The production qualifier's shape. qualify() itself lives in db_gateway.hpp
+/// and has its own tests; planning takes it as a parameter so this file does not
+/// need the database client.
+std::string testQualify(const std::string& project, const std::string& collection) {
+    if (project.empty() || project == "default") return collection;
+    return project + ":" + collection;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------
+// minuteFloor
+// ---------------------------------------------------------------------------
+
+TEST(MinuteFloor, TruncatesToTheMinute) {
+    EXPECT_EQ(minuteFloor(0), 0);
+    EXPECT_EQ(minuteFloor(59), 0);
+    EXPECT_EQ(minuteFloor(60), 60);
+    EXPECT_EQ(minuteFloor(119), 60);
+    EXPECT_EQ(minuteFloor(1'760'000'045), 1'760'000'040);
+}
+
+TEST(MinuteFloor, ClampsNonPositive) {
+    // Truncation toward zero would round a negative timestamp the wrong way.
+    EXPECT_EQ(minuteFloor(-1), 0);
+    EXPECT_EQ(minuteFloor(-61), 0);
+}
+
+// ---------------------------------------------------------------------------
+// cronDue
+// ---------------------------------------------------------------------------
+
+TEST(CronDue, FiresOnAMatchingMinuteThatHasNotFired) {
+    // 1'760'000'040 / 60 = 29'333'334, divisible by 2.
+    EXPECT_TRUE(cronDue(everyMinutes(2), 1'760'000'040, 0));
+}
+
+TEST(CronDue, DoesNotFireOnANonMatchingMinute) {
+    EXPECT_FALSE(cronDue(everyMinutes(2), 1'760'000'100, 0));
+}
+
+TEST(CronDue, DoesNotFireTwiceInTheSameMinute) {
+    const std::time_t t = 1'760'000'040;
+    ASSERT_TRUE(cronDue(everyMinutes(2), t, 0));
+    // Three ticks land inside one minute at the default 20 s interval; only the
+    // first may produce a job.
+    EXPECT_FALSE(cronDue(everyMinutes(2), t, minuteFloor(t)));
+    EXPECT_FALSE(cronDue(everyMinutes(2), t + 20, minuteFloor(t)));
+    EXPECT_FALSE(cronDue(everyMinutes(2), t + 59, minuteFloor(t)));
+}
+
+TEST(CronDue, FiresAgainOnTheNextMatchingMinute) {
+    const std::time_t t = 1'760'000'040;
+    EXPECT_TRUE(cronDue(everyMinutes(2), t + 120, minuteFloor(t)));
+}
+
+TEST(CronDue, SkipsMissedMinutesRatherThanReplayingThem) {
+    // The documented restart behaviour: an hourly function whose server was down
+    // for three hours fires ONCE at the next matching minute. Nothing in the
+    // decision looks backwards, so there is no backlog to replay.
+    const auto hourly = [](std::time_t t) { return (minuteFloor(t) / 60) % 60 == 0; };
+    const std::time_t downAt = 1'760'000'040;              // whatever it was
+    const std::time_t backAt = downAt + 3 * 3600;          // three hours later
+    // Fresh process: lastFired is 0.
+    int fires = 0;
+    for (std::time_t t = backAt; t < backAt + 60; t += 20)
+        if (cronDue(hourly, t, fires ? minuteFloor(backAt) : 0)) ++fires;
+    EXPECT_LE(fires, 1);
+}
+
+TEST(CronDue, AClockSteppedBackwardsCannotRefireAMinute) {
+    const std::time_t t = 1'760'000'040;
+    // NTP drags the clock back two minutes. The minute is at or before the one
+    // that already fired, so nothing fires again.
+    EXPECT_FALSE(cronDue(everyMinutes(2), t - 120, minuteFloor(t)));
+    EXPECT_FALSE(cronDue(everyMinutes(2), t, minuteFloor(t)));
+}
+
+TEST(CronDue, LastFiredZeroMeansNeverFired) {
+    // 0 must not be read as "fired at the epoch", or a schedule matching the
+    // epoch minute would be stuck.
+    EXPECT_TRUE(cronDue([](std::time_t) { return true; }, 0, 0));
+}
+
+// ---------------------------------------------------------------------------
+// single flight
+// ---------------------------------------------------------------------------
+
+TEST(SingleFlight, SkipsOnlyWhenRequestedAndActive) {
+    EXPECT_TRUE(skipForSingleFlight(true, true));
+    EXPECT_FALSE(skipForSingleFlight(true, false));
+    // Explicitly off: the author asked for overlapping runs and gets them.
+    EXPECT_FALSE(skipForSingleFlight(false, true));
+    EXPECT_FALSE(skipForSingleFlight(false, false));
+}
+
+TEST(SingleFlight, CronDescriptorsDefaultToIt) {
+    // The behaviour the scheduler relies on; asserted here so a change to the
+    // descriptor default cannot quietly turn stacking back on.
+    const functions::ParseResult p = functions::parseDescriptor(
+        {{"id", "nightly"}, {"type", "cron"}, {"schedule", "0 3 * * *"}});
+    ASSERT_TRUE(p.ok) << p.error;
+    EXPECT_TRUE(p.descriptor.singleFlight);
+}
+
+// ---------------------------------------------------------------------------
+// collection names and the never-watch guard
+// ---------------------------------------------------------------------------
+
+TEST(UnqualifiedCollection, StripsTheProjectPrefix) {
+    EXPECT_EQ(unqualifiedCollection("acme:docs"), "docs");
+    EXPECT_EQ(unqualifiedCollection("docs"), "docs");
+    EXPECT_EQ(unqualifiedCollection(""), "");
+}
+
+TEST(NeverWatched, RefusesTheRuntimesOwnBookkeeping) {
+    // The queue is the dangerous one: watching it makes every enqueue an event
+    // and every event an enqueue, a loop with no user function in it at all.
+    EXPECT_TRUE(isNeverWatched("vectorapi_function_jobs"));
+    EXPECT_TRUE(isNeverWatched("default:vectorapi_function_jobs"));
+    EXPECT_TRUE(isNeverWatched("acme:vectorapi_functions"));
+    EXPECT_TRUE(isNeverWatched("acme:vectorapi_function_runs"));
+    EXPECT_TRUE(isNeverWatched("vectorapi_keys"));
+    EXPECT_TRUE(isNeverWatched("vectorapi_settings"));
+    EXPECT_TRUE(isNeverWatched("acme:vectorapi_collections"));
+    // Reserved underscore prefix (and the DB v2.3.1 misroute gotcha).
+    EXPECT_TRUE(isNeverWatched("acme:_internal"));
+    EXPECT_TRUE(isNeverWatched("_internal"));
+}
+
+TEST(NeverWatched, AllowsOrdinaryCollections) {
+    EXPECT_FALSE(isNeverWatched("acme:docs"));
+    EXPECT_FALSE(isNeverWatched("docs"));
+    // Near misses must stay watchable: the rule is a prefix on the unqualified
+    // name, not a substring anywhere.
+    EXPECT_FALSE(isNeverWatched("acme:my_vectorapi_notes"));
+    EXPECT_FALSE(isNeverWatched("vectorapi"));
+}
+
+// ---------------------------------------------------------------------------
+// event type mapping
+// ---------------------------------------------------------------------------
+
+TEST(DbEventMapping, MapsTheThreeTriggerEvents) {
+    EXPECT_EQ(dbEventFromClientString("insert"), functions::DbEvent::Insert);
+    EXPECT_EQ(dbEventFromClientString("update"), functions::DbEvent::Update);
+    EXPECT_EQ(dbEventFromClientString("delete"), functions::DbEvent::Delete);
+    // The client emits lower case; tolerate the descriptor's spelling too.
+    EXPECT_EQ(dbEventFromClientString("INSERT"), functions::DbEvent::Insert);
+}
+
+TEST(DbEventMapping, ExpiryAndInvalidationAreNotTriggers) {
+    // A TTL eviction is not somebody deleting a document. Mapping it to DELETE
+    // would turn a retention policy into a traffic generator.
+    EXPECT_FALSE(dbEventFromClientString("expire").has_value());
+    EXPECT_FALSE(dbEventFromClientString("invalidate").has_value());
+    EXPECT_FALSE(dbEventFromClientString("unknown").has_value());
+    EXPECT_FALSE(dbEventFromClientString("").has_value());
+}
+
+// ---------------------------------------------------------------------------
+// eventTriggers
+// ---------------------------------------------------------------------------
+
+TEST(EventTriggers, MatchesCollectionAndEvent) {
+    const functions::ParseResult p =
+        functions::parseDescriptor(dbDescriptor("reindex", "docs", "INSERT"));
+    ASSERT_TRUE(p.ok) << p.error;
+    EXPECT_TRUE(eventTriggers(p.descriptor, "acme:docs", "acme:docs", "insert"));
+}
+
+TEST(EventTriggers, RejectsTheWrongEvent) {
+    const functions::ParseResult p =
+        functions::parseDescriptor(dbDescriptor("reindex", "docs", "INSERT"));
+    ASSERT_TRUE(p.ok) << p.error;
+    EXPECT_FALSE(eventTriggers(p.descriptor, "acme:docs", "acme:docs", "update"));
+    EXPECT_FALSE(eventTriggers(p.descriptor, "acme:docs", "acme:docs", "delete"));
+    EXPECT_FALSE(eventTriggers(p.descriptor, "acme:docs", "acme:docs", "expire"));
+}
+
+TEST(EventTriggers, RejectsAnotherProjectsCollectionOfTheSameName) {
+    // The comparison is on the QUALIFIED name, so acme's function cannot be fed
+    // by beta's writes. This is the one that matters for tenant isolation.
+    const functions::ParseResult p =
+        functions::parseDescriptor(dbDescriptor("reindex", "docs", "INSERT"));
+    ASSERT_TRUE(p.ok) << p.error;
+    EXPECT_FALSE(eventTriggers(p.descriptor, "acme:docs", "beta:docs", "insert"));
+    EXPECT_FALSE(eventTriggers(p.descriptor, "acme:docs", "docs", "insert"));
+}
+
+TEST(EventTriggers, RejectsNonDbDescriptors) {
+    const functions::ParseResult http = functions::parseDescriptor(
+        {{"id", "kb"}, {"type", "http"}, {"route", "/kb"}});
+    ASSERT_TRUE(http.ok) << http.error;
+    EXPECT_FALSE(eventTriggers(http.descriptor, "acme:docs", "acme:docs", "insert"));
+
+    const functions::ParseResult cron = functions::parseDescriptor(
+        {{"id", "nightly"}, {"type", "cron"}, {"schedule", "0 3 * * *"}});
+    ASSERT_TRUE(cron.ok) << cron.error;
+    EXPECT_FALSE(eventTriggers(cron.descriptor, "acme:docs", "acme:docs", "insert"));
+}
+
+TEST(EventTriggers, NeverFiresOnAReservedCollection) {
+    // Even if a plan somehow carried one, the predicate that lets a job be
+    // created refuses it.
+    const functions::ParseResult p = functions::parseDescriptor(
+        dbDescriptor("loop", "vectorapi_function_jobs", "INSERT"));
+    ASSERT_TRUE(p.ok) << p.error;
+    EXPECT_FALSE(eventTriggers(p.descriptor, "vectorapi_function_jobs",
+                               "vectorapi_function_jobs", "insert"));
+}
+
+// ---------------------------------------------------------------------------
+// the depth guard
+// ---------------------------------------------------------------------------
+
+TEST(DepthForEvent, CountsGenerationsAndRefusesPastTheLimit) {
+    EXPECT_EQ(depthForEvent(0, 3), std::optional<uint32_t>(1));
+    EXPECT_EQ(depthForEvent(1, 3), std::optional<uint32_t>(2));
+    EXPECT_EQ(depthForEvent(2, 3), std::optional<uint32_t>(3));
+    // The fourth generation is refused - this is the loop guard.
+    EXPECT_FALSE(depthForEvent(3, 3).has_value());
+    EXPECT_FALSE(depthForEvent(9, 3).has_value());
+}
+
+TEST(DepthForEvent, MaxDepthZeroDisablesEventChaining) {
+    EXPECT_FALSE(depthForEvent(0, 0).has_value());
+}
+
+TEST(DepthForEvent, CannotOverflow) {
+    // The arithmetic is done in 64 bits so a clamped-but-huge depth still
+    // refuses rather than wrapping to 0 and firing.
+    EXPECT_FALSE(depthForEvent(4294967295u, 3).has_value());
+}
+
+// ---------------------------------------------------------------------------
+// the watch plan
+// ---------------------------------------------------------------------------
+
+TEST(WatchPlan, AddsAnEnabledValidDbFunction) {
+    FunctionWatchPlan plan;
+    EXPECT_TRUE(planAddFunction(plan, testQualify, "acme", "reindex",
+                                dbDescriptor("reindex", "docs", "INSERT"), true, true));
+    planFinalise(plan);
+    ASSERT_EQ(plan.collections.size(), 1u);
+    EXPECT_EQ(plan.collections[0], "acme:docs");
+    ASSERT_EQ(plan.targets.at("acme:docs").size(), 1u);
+    EXPECT_EQ(plan.targets.at("acme:docs")[0].functionId, "reindex");
+    EXPECT_EQ(plan.targets.at("acme:docs")[0].project, "acme");
+}
+
+TEST(WatchPlan, SkipsDisabledAndInvalidFunctions) {
+    FunctionWatchPlan plan;
+    const nlohmann::json on = dbDescriptor("reindex", "docs", "INSERT");
+    EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "reindex", on, false, true));
+    EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "reindex", on, true, false));
+    planFinalise(plan);
+    EXPECT_TRUE(plan.collections.empty());
+}
+
+TEST(WatchPlan, SkipsNonDbAndUnparseableDescriptors) {
+    FunctionWatchPlan plan;
+    EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "kb",
+                                 {{"id", "kb"}, {"type", "http"}, {"route", "/kb"}},
+                                 true, true));
+    EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "nightly",
+                                 {{"id", "nightly"}, {"type", "cron"},
+                                  {"schedule", "0 3 * * *"}}, true, true));
+    // A descriptor that does not parse is data, not an exception.
+    EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "broken",
+                                 {{"id", "broken"}, {"type", "db"}}, true, true));
+    EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "empty",
+                                 nlohmann::json::object(), true, true));
+    planFinalise(plan);
+    EXPECT_TRUE(plan.collections.empty());
+}
+
+TEST(WatchPlan, NeverPlansAReservedCollection) {
+    FunctionWatchPlan plan;
+    for (const char* table : {"vectorapi_function_jobs", "vectorapi_functions",
+                              "vectorapi_function_runs", "vectorapi_keys",
+                              "vectorapi_settings", "_hidden"}) {
+        EXPECT_FALSE(planAddFunction(plan, testQualify, "acme", "loop",
+                                     dbDescriptor("loop", table, "INSERT"), true, true))
+            << table;
+    }
+    planFinalise(plan);
+    EXPECT_TRUE(plan.collections.empty());
+}
+
+TEST(WatchPlan, SeveralFunctionsCanShareOneCollection) {
+    FunctionWatchPlan plan;
+    ASSERT_TRUE(planAddFunction(plan, testQualify, "acme", "b-on-insert",
+                                dbDescriptor("b-on-insert", "docs", "INSERT"), true, true));
+    ASSERT_TRUE(planAddFunction(plan, testQualify, "acme", "a-on-delete",
+                                dbDescriptor("a-on-delete", "docs", "DELETE"), true, true));
+    planFinalise(plan);
+    ASSERT_EQ(plan.collections.size(), 1u);
+    const auto& targets = plan.targets.at("acme:docs");
+    ASSERT_EQ(targets.size(), 2u);
+    EXPECT_EQ(targets[0].functionId, "a-on-delete");   // ordered, not registry order
+    EXPECT_EQ(targets[1].functionId, "b-on-insert");
+}
+
+TEST(WatchPlan, TheDefaultProjectQualifiesToABareName) {
+    FunctionWatchPlan plan;
+    ASSERT_TRUE(planAddFunction(plan, testQualify, "default", "reindex",
+                                dbDescriptor("reindex", "docs", "INSERT"), true, true));
+    planFinalise(plan);
+    ASSERT_EQ(plan.collections.size(), 1u);
+    EXPECT_EQ(plan.collections[0], "docs");
+}
+
+TEST(WatchPlan, TheCollectionSetIsStableAcrossRegistryOrder) {
+    // This is what stops refresh() from tearing down the subscribe stream every
+    // time it polls: two plans over the same functions must produce an IDENTICAL
+    // collection vector whatever order the database returned rows in.
+    FunctionWatchPlan a;
+    planAddFunction(a, testQualify, "acme", "f1", dbDescriptor("f1", "docs", "INSERT"), true, true);
+    planAddFunction(a, testQualify, "beta", "f2", dbDescriptor("f2", "notes", "UPDATE"), true, true);
+    planAddFunction(a, testQualify, "acme", "f3", dbDescriptor("f3", "docs", "DELETE"), true, true);
+    planFinalise(a);
+
+    FunctionWatchPlan b;
+    planAddFunction(b, testQualify, "acme", "f3", dbDescriptor("f3", "docs", "DELETE"), true, true);
+    planAddFunction(b, testQualify, "acme", "f1", dbDescriptor("f1", "docs", "INSERT"), true, true);
+    planAddFunction(b, testQualify, "beta", "f2", dbDescriptor("f2", "notes", "UPDATE"), true, true);
+    planFinalise(b);
+
+    EXPECT_EQ(a.collections, b.collections);
+    EXPECT_EQ(a.collections, (std::vector<std::string>{"acme:docs", "beta:notes"}));
+}
+
+TEST(WatchPlan, DisablingAFunctionShrinksTheWatchedSet) {
+    // The other half of the rebuild trigger: the set DOES change when the last
+    // function on a collection goes away, and then the stream must be reopened.
+    FunctionWatchPlan before;
+    planAddFunction(before, testQualify, "acme", "f1",
+                    dbDescriptor("f1", "docs", "INSERT"), true, true);
+    planAddFunction(before, testQualify, "acme", "f2",
+                    dbDescriptor("f2", "notes", "INSERT"), true, true);
+    planFinalise(before);
+
+    FunctionWatchPlan after;
+    planAddFunction(after, testQualify, "acme", "f1",
+                    dbDescriptor("f1", "docs", "INSERT"), true, true);
+    planAddFunction(after, testQualify, "acme", "f2",
+                    dbDescriptor("f2", "notes", "INSERT"), /*enabled*/ false, true);
+    planFinalise(after);
+
+    EXPECT_NE(before.collections, after.collections);
+    EXPECT_EQ(after.collections, (std::vector<std::string>{"acme:docs"}));
+}
+
+TEST(WatchPlan, SingleFlightSurvivesIntoTheTarget) {
+    // A target carries the whole descriptor, so the watcher's single-flight
+    // decision reads the same flag the author declared.
+    FunctionWatchPlan plan;
+    ASSERT_TRUE(planAddFunction(plan, testQualify, "acme", "slow",
+                                dbDescriptor("slow", "docs", "INSERT", /*singleFlight*/ true),
+                                true, true));
+    planFinalise(plan);
+    EXPECT_TRUE(plan.targets.at("acme:docs")[0].descriptor.singleFlight);
+}
+
+// --------------------------------------------------------------------------
+// provenance: depth comes from the audit trail, not from the document
+// --------------------------------------------------------------------------
+
+TEST(TriggerDepth, AnOrdinaryWriteIsDepthZero) {
+    // Almost every event is this: a human, a client, another service. None of
+    // them writes an actor that looks like a function.
+    EXPECT_EQ(depthFromActor(""), 0u);
+    EXPECT_EQ(depthFromActor("alice"), 0u);
+    EXPECT_EQ(depthFromActor("key-7"), 0u);
+    EXPECT_EQ(depthFromActor("service:importer"), 0u);
+}
+
+TEST(TriggerDepth, ReadsTheDepthAFunctionStamped) {
+    // The shape runner/src/host_context.cpp writes: fn:<project>/<id>:<depth>
+    EXPECT_EQ(depthFromActor("fn:acme/kb-search:0"), 0u);
+    EXPECT_EQ(depthFromActor("fn:acme/kb-search:1"), 1u);
+    EXPECT_EQ(depthFromActor("fn:acme/normalise:3"), 3u);
+}
+
+TEST(TriggerDepth, AMalformedActorIsNotTakenAsShallow) {
+    // Unparseable must mean 0 (an ordinary write) rather than throwing, but it
+    // must never be mistaken for a function write at a lower depth, which
+    // would hand a real chain a fresh budget.
+    EXPECT_EQ(depthFromActor("fn:acme/kb-search"), 0u) << "no depth at all";
+    EXPECT_EQ(depthFromActor("fn:acme/kb-search:"), 0u) << "empty depth";
+    EXPECT_EQ(depthFromActor("fn:acme/kb-search:x"), 0u) << "non-numeric";
+    EXPECT_EQ(depthFromActor("fn:acme/kb-search:-2"), 0u) << "negative";
+    EXPECT_EQ(depthFromActor("fn:"), 0u);
+}
+
+TEST(TriggerDepth, ClampsAHostileValue) {
+    // A corrupt or crafted actor must not wrap to a small depth.
+    EXPECT_EQ(depthFromActor("fn:a/b:99999999999999999999"), 1000u);
+    EXPECT_EQ(depthFromActor("fn:a/b:4294967296"), 1000u);
+}
+
+TEST(TriggerDepth, TheProjectAndFunctionIdAreNotParsedAsDepth) {
+    // The LAST colon separates the depth, so a function id is never mistaken
+    // for one even if ids ever grow colons.
+    EXPECT_EQ(depthFromActor("fn:acme/a:b:2"), 2u);
+}
+
+// ---------------------------------------------------------------------------
+// The zone reaches the due decision
+// ---------------------------------------------------------------------------
+//
+// cronDue() takes a matcher, so these build the matcher the way tickOnce() does
+// - CronExpr::matchesIn bound to the descriptor's tz - and assert the whole
+// chain from the script's `on` block to "is it due". A test that only exercised
+// the engine would still pass if the scheduler dropped the zone on the floor,
+// which is exactly the bug this covers.
+
+namespace {
+
+/// The production matcher, assembled from a descriptor the same way the
+/// scheduler assembles it.
+std::function<bool(std::time_t)> matcherFor(const nlohmann::json& on) {
+    const functions::ParseResult parsed = functions::parseDescriptor(on);
+    EXPECT_TRUE(parsed.ok) << parsed.error;
+    const std::optional<functions::CronExpr> expr =
+        functions::CronExpr::parse(parsed.descriptor.schedule, nullptr);
+    EXPECT_TRUE(expr.has_value());
+    const functions::CronExpr e = expr.value_or(functions::CronExpr{});
+    const std::string zone = parsed.descriptor.timezone;
+    return [e, zone](std::time_t t) { return e.matchesIn(t, zone); };
+}
+
+std::time_t utcAt(int year, int mon, int day, int hour, int min) {
+    std::tm tm{};
+    tm.tm_year = year - 1900;
+    tm.tm_mon = mon - 1;
+    tm.tm_mday = day;
+    tm.tm_hour = hour;
+    tm.tm_min = min;
+    return timegm(&tm);
+}
+
+nlohmann::json cronOn(const std::string& schedule, const std::string& tz = {}) {
+    nlohmann::json on{{"id", "daily"}, {"type", "cron"}, {"schedule", schedule}};
+    if (!tz.empty()) on["tz"] = tz;
+    return on;
+}
+
+} // namespace
+
+TEST(CronDueZone, TheDescriptorsZoneDecidesTheHour) {
+    // The deployed bug: tz was dropped and the schedule ran in UTC, so an 08:00
+    // Budapest report went out at 09:00 local in winter and 10:00 in summer.
+    const auto budapest = matcherFor(cronOn("0 8 * * *", "Europe/Budapest"));
+    EXPECT_TRUE(cronDue(budapest, utcAt(2026, 1, 15, 7, 0), 0));   // 08:00 CET
+    EXPECT_FALSE(cronDue(budapest, utcAt(2026, 1, 15, 8, 0), 0));
+    EXPECT_TRUE(cronDue(budapest, utcAt(2026, 7, 15, 6, 0), 0));   // 08:00 CEST
+    EXPECT_FALSE(cronDue(budapest, utcAt(2026, 7, 15, 8, 0), 0));
+
+    // No tz: unchanged, 08:00 UTC all year.
+    const auto plain = matcherFor(cronOn("0 8 * * *"));
+    EXPECT_TRUE(cronDue(plain, utcAt(2026, 1, 15, 8, 0), 0));
+    EXPECT_TRUE(cronDue(plain, utcAt(2026, 7, 15, 8, 0), 0));
+    EXPECT_FALSE(cronDue(plain, utcAt(2026, 1, 15, 7, 0), 0));
+}
+
+TEST(CronDueZone, TheSkippedHourStillProducesOneDueMinute) {
+    // Europe/Budapest 2026-03-29: 02:30 local does not exist, and the run must
+    // not be lost. Walked minute by minute the way the scheduler ticks, with
+    // lastFired carried forward, so a double fire would show up as two.
+    const auto m = matcherFor(cronOn("30 2 * * *", "Europe/Budapest"));
+    int fired = 0;
+    std::time_t lastFired = 0;
+    for (std::time_t t = utcAt(2026, 3, 28, 22, 0); t < utcAt(2026, 3, 29, 12, 0); t += 60) {
+        if (cronDue(m, t, lastFired)) {
+            ++fired;
+            lastFired = minuteFloor(t);
+        }
+    }
+    EXPECT_EQ(fired, 1);
+}
+
+TEST(CronDueZone, TheRepeatedHourProducesOneDueMinuteNotTwo) {
+    // Europe/Budapest 2026-10-25: 02:30 local happens twice. Once is the answer
+    // the time zone seam commits to, and lastFired alone would not save us -
+    // the two occurrences are an hour apart, in different minutes.
+    const auto m = matcherFor(cronOn("30 2 * * *", "Europe/Budapest"));
+    int fired = 0;
+    std::time_t lastFired = 0;
+    for (std::time_t t = utcAt(2026, 10, 24, 22, 0); t < utcAt(2026, 10, 25, 12, 0); t += 60) {
+        if (cronDue(m, t, lastFired)) {
+            ++fired;
+            lastFired = minuteFloor(t);
+        }
+    }
+    EXPECT_EQ(fired, 1);
+}
+
+TEST(CronDueZone, SouthernHemisphereTransitionsAreHonouredToo) {
+    const auto m = matcherFor(cronOn("30 2 * * *", "Australia/Sydney"));
+    // Clocks forward: 02:30 AEST skipped on 2026-10-04, fires at the gap end.
+    EXPECT_TRUE(cronDue(m, utcAt(2026, 10, 3, 16, 0), 0));
+    // Clocks back: 02:30 on 2026-04-05 happens twice; only the first counts.
+    EXPECT_TRUE(cronDue(m, utcAt(2026, 4, 4, 15, 30), 0));
+    EXPECT_FALSE(cronDue(m, utcAt(2026, 4, 4, 16, 30), 0));
+}
+
+TEST(CronDueZone, ANonHourOffsetIsCarriedThrough) {
+    // Asia/Kathmandu is UTC+05:45. If anything on the path rounded to whole
+    // hours, this is where it shows.
+    const auto m = matcherFor(cronOn("0 8 * * *", "Asia/Kathmandu"));
+    EXPECT_TRUE(cronDue(m, utcAt(2026, 6, 1, 2, 15), 0));
+    EXPECT_FALSE(cronDue(m, utcAt(2026, 6, 1, 2, 0), 0));
+}
+
+TEST(CronDueZone, AnUnknownZoneIsRefusedAtParseTimeNotSilentlyRunInUtc) {
+    // The first line of defence: the descriptor never stores a zone this host
+    // cannot resolve, so the scheduler's own check is a belt-and-braces for
+    // rows written before it existed.
+    const functions::ParseResult bad =
+        functions::parseDescriptor(cronOn("0 8 * * *", "Europe/Atlantis"));
+    EXPECT_FALSE(bad.ok);
+    EXPECT_NE(bad.error.find("time zone"), std::string::npos) << bad.error;
+}

+ 680 - 0
tests/test_functions_cron.cpp

@@ -0,0 +1,680 @@
+// Unit tests for the cron engine. Pure: no database, no network, no clock -
+// every timestamp here is constructed, so these run anywhere the compiler does.
+//
+// Why so many cases: validating an expression and firing on it are the same
+// code now, so a hole here is a schedule that validates on push and then never
+// fires, which looks exactly like a broken scheduler.
+#include <gtest/gtest.h>
+
+#include <cstdlib>
+#include <ctime>
+#include <string>
+#include <vector>
+
+#include "functions/cron.hpp"
+
+using svapi::functions::CronExpr;
+using svapi::functions::cronExpressionValid;
+
+namespace {
+
+/// A UTC timestamp from calendar parts. timegm, never mktime: a test that
+/// depended on the host's TZ would pass in CI and fail on a laptop.
+std::time_t utc(int year, int mon, int day, int hour, int min, int sec = 0) {
+    std::tm tm{};
+    tm.tm_year = year - 1900;
+    tm.tm_mon = mon - 1;
+    tm.tm_mday = day;
+    tm.tm_hour = hour;
+    tm.tm_min = min;
+    tm.tm_sec = sec;
+    return timegm(&tm);
+}
+
+std::string iso(std::time_t t) {
+    std::tm tm{};
+    gmtime_r(&t, &tm);
+    char buf[32];
+    std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);
+    return buf;
+}
+
+CronExpr ok(const std::string& expr) {
+    std::string err = "(no error reported)";
+    const std::optional<CronExpr> c = CronExpr::parse(expr, &err);
+    EXPECT_TRUE(c.has_value()) << "'" << expr << "' should parse: " << err;
+    return c.value_or(CronExpr{});
+}
+
+void bad(const std::string& expr) {
+    std::string err;
+    EXPECT_FALSE(CronExpr::parse(expr, &err).has_value()) << "'" << expr << "' should be rejected";
+    EXPECT_FALSE(err.empty()) << "'" << expr << "' rejected without an explanation";
+}
+
+} // namespace
+
+// ------------------------------------------------------------------ grammar
+
+TEST(Cron, AcceptsTheWholeGrammar) {
+    ok("* * * * *");
+    ok("0 0 1 1 0");
+    ok("59 23 31 12 6");
+    ok("*/5 * * * *");
+    ok("0,15,30,45 * * * *");
+    ok("0-59 0-23 1-31 1-12 0-7");
+    ok("1-5/2 * * * *");
+    ok("5/10 * * * *"); // a start value with a step, like Vixie cron
+    ok("0 3 * * 7");    // 7 is Sunday
+    ok("0 0 1 JAN MON");
+    ok("0 0 1 jan-dec sun-sat");
+    ok("0 0 1 Feb Fri");
+    ok("  0 3 * * 0  ");    // leading and trailing whitespace is not a field
+    ok("0\t3\t*\t*\t0");    // any whitespace separates
+    ok("0  3   *  *  0");   // runs of whitespace collapse
+    ok("007 03 * * *");     // leading zeros are still digits
+    ok("0 0 29 2 *");       // Feb 29: fires only in a leap year, but legal
+    ok("*/1 */1 */1 */1 */1");
+}
+
+TEST(Cron, RejectsMalformedExpressions) {
+    bad("");
+    bad("   ");
+    bad("* * * *");       // four fields
+    bad("* * * * * *");   // six fields (no seconds field in this dialect)
+    bad("* * * * * * *");
+    bad("*/0 * * * *");   // a zero step would never fire
+    bad("* */0 * * *");
+    bad("5-1 * * * *");   // reversed range
+    bad("FRI-MON * * * 1-0");
+    bad("a * * * *");     // non-numeric, non-alias
+    bad("monday * * * *");
+    bad("* * * * monday"); // only the three-letter alias is accepted
+    bad("0, * * * *");     // trailing comma
+    bad(",0 * * * *");     // leading comma
+    bad("0,,30 * * * *");  // empty list item
+    bad("60 * * * *");     // out of range, every field
+    bad("* 24 * * *");
+    bad("* * 0 * *");
+    bad("* * 32 * *");
+    bad("* * * 0 *");
+    bad("* * * 13 *");
+    bad("* * * * 8");
+    bad("-5 * * * *");
+    bad("1-2-3 * * * *");
+    bad("* * * * 1-2-3");
+    bad("5/ * * * *");      // empty step
+    bad("5/2/3 * * * *");   // two steps
+    bad("*/x * * * *");     // non-numeric step
+    bad("*/100 * * * *");   // step longer than two digits is refused outright
+    bad("99999999999999999999 * * * *"); // must not throw on an absurd digit run
+    bad("* * JAN * *");     // month aliases do not apply to day-of-month
+    bad("* * * * JAN");     // nor month aliases to day-of-week
+    bad("SUN * * * *");     // nor day aliases to the minute field
+}
+
+TEST(Cron, ParseNeverThrowsAndToleratesANullError) {
+    // A script author's typo is data, not an exception. Also: `error` is
+    // documented as optional, so a caller that does not want the text must not
+    // crash the server.
+    EXPECT_NO_THROW({
+        EXPECT_FALSE(CronExpr::parse("totally bogus ! ? #", nullptr).has_value());
+        EXPECT_TRUE(CronExpr::parse("* * * * *", nullptr).has_value());
+    });
+}
+
+TEST(Cron, ValidHelperAgreesWithParse) {
+    std::string err;
+    EXPECT_TRUE(cronExpressionValid("0 3 * * *", &err));
+    EXPECT_TRUE(err.empty());
+    EXPECT_FALSE(cronExpressionValid("0 3 * *", &err));
+    EXPECT_FALSE(err.empty());
+    EXPECT_TRUE(cronExpressionValid("* * * * *", nullptr));
+    EXPECT_FALSE(cronExpressionValid("nope", nullptr));
+}
+
+TEST(Cron, ErrorNamesTheOffendingField) {
+    std::string err;
+    CronExpr::parse("* * * 13 *", &err);
+    EXPECT_NE(err.find("month"), std::string::npos) << err;
+    CronExpr::parse("* * * *", &err);
+    EXPECT_NE(err.find("5"), std::string::npos) << err;
+}
+
+// ------------------------------------------------------------------ matches
+
+TEST(Cron, EveryMinuteMatchesEverything) {
+    const CronExpr c = ok("* * * * *");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 7, 13, 45)));
+    EXPECT_TRUE(c.matches(utc(2000, 1, 1, 0, 0)));
+}
+
+TEST(Cron, SecondsAreIgnored) {
+    // Minute resolution: whether the scheduler ticks at :00 or :59 of the
+    // minute must not change the answer.
+    const CronExpr c = ok("30 4 * * *");
+    for (const int sec : {0, 1, 30, 59}) EXPECT_TRUE(c.matches(utc(2026, 3, 1, 4, 30, sec))) << sec;
+    EXPECT_FALSE(c.matches(utc(2026, 3, 1, 4, 31, 0)));
+}
+
+TEST(Cron, MatchesEachFieldIndependently) {
+    const CronExpr c = ok("30 4 15 6 *");
+    EXPECT_TRUE(c.matches(utc(2026, 6, 15, 4, 30)));
+    EXPECT_FALSE(c.matches(utc(2026, 6, 15, 4, 31))); // minute
+    EXPECT_FALSE(c.matches(utc(2026, 6, 15, 5, 30))); // hour
+    EXPECT_FALSE(c.matches(utc(2026, 6, 16, 4, 30))); // day of month
+    EXPECT_FALSE(c.matches(utc(2026, 7, 15, 4, 30))); // month
+}
+
+TEST(Cron, MatchesSteps) {
+    const CronExpr c = ok("*/15 * * * *");
+    EXPECT_TRUE(c.matches(utc(2026, 1, 1, 0, 0)));
+    EXPECT_TRUE(c.matches(utc(2026, 1, 1, 0, 15)));
+    EXPECT_TRUE(c.matches(utc(2026, 1, 1, 0, 30)));
+    EXPECT_TRUE(c.matches(utc(2026, 1, 1, 0, 45)));
+    EXPECT_FALSE(c.matches(utc(2026, 1, 1, 0, 1)));
+    EXPECT_FALSE(c.matches(utc(2026, 1, 1, 0, 59)));
+}
+
+TEST(Cron, MatchesRangeWithStep) {
+    const CronExpr c = ok("10-20/5 * * * *");
+    for (const int m : {10, 15, 20}) EXPECT_TRUE(c.matches(utc(2026, 1, 1, 0, m))) << m;
+    for (const int m : {9, 11, 14, 21, 25}) EXPECT_FALSE(c.matches(utc(2026, 1, 1, 0, m))) << m;
+}
+
+TEST(Cron, MatchesValueWithStep) {
+    // "50/4" means from 50 to the field maximum in fours, as Vixie cron reads
+    // it - not "50 only", and not every fourth minute of the hour.
+    const CronExpr c = ok("50/4 * * * *");
+    for (const int m : {50, 54, 58}) EXPECT_TRUE(c.matches(utc(2026, 1, 1, 0, m))) << m;
+    for (const int m : {0, 2, 46, 51, 59}) EXPECT_FALSE(c.matches(utc(2026, 1, 1, 0, m))) << m;
+}
+
+TEST(Cron, MatchesListsAndRanges) {
+    const CronExpr c = ok("0,30 9-17 * * *");
+    EXPECT_TRUE(c.matches(utc(2026, 1, 1, 9, 0)));
+    EXPECT_TRUE(c.matches(utc(2026, 1, 1, 17, 30)));
+    EXPECT_FALSE(c.matches(utc(2026, 1, 1, 18, 0)));
+    EXPECT_FALSE(c.matches(utc(2026, 1, 1, 8, 59)));
+    EXPECT_FALSE(c.matches(utc(2026, 1, 1, 12, 15)));
+}
+
+TEST(Cron, MatchesMonthAliasesCaseInsensitively) {
+    const CronExpr c = ok("0 0 1 FeB,mar *");
+    EXPECT_TRUE(c.matches(utc(2026, 2, 1, 0, 0)));
+    EXPECT_TRUE(c.matches(utc(2026, 3, 1, 0, 0)));
+    EXPECT_FALSE(c.matches(utc(2026, 4, 1, 0, 0)));
+    // The alias must resolve to the same bit as the number.
+    const CronExpr n = ok("0 0 1 2,3 *");
+    for (const int mon : {1, 2, 3, 4, 12})
+        EXPECT_EQ(c.matches(utc(2026, mon, 1, 0, 0)), n.matches(utc(2026, mon, 1, 0, 0))) << mon;
+}
+
+TEST(Cron, MatchesDayOfWeekAliasesAndSevenAsSunday) {
+    // 2026-10-07 is a Wednesday; 2026-10-11 a Sunday.
+    EXPECT_TRUE(ok("0 0 * * WED").matches(utc(2026, 10, 7, 0, 0)));
+    EXPECT_FALSE(ok("0 0 * * WED").matches(utc(2026, 10, 8, 0, 0)));
+    EXPECT_TRUE(ok("0 0 * * 7").matches(utc(2026, 10, 11, 0, 0)));
+    EXPECT_TRUE(ok("0 0 * * 0").matches(utc(2026, 10, 11, 0, 0)));
+    EXPECT_TRUE(ok("0 0 * * SUN").matches(utc(2026, 10, 11, 0, 0)));
+    // A range that runs through 7 must still include Sunday and Friday.
+    const CronExpr c = ok("0 0 * * 5-7");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 9, 0, 0)));   // Friday
+    EXPECT_TRUE(c.matches(utc(2026, 10, 10, 0, 0)));  // Saturday
+    EXPECT_TRUE(c.matches(utc(2026, 10, 11, 0, 0)));  // Sunday
+    EXPECT_FALSE(c.matches(utc(2026, 10, 12, 0, 0))); // Monday
+}
+
+TEST(Cron, EverythingIsUtcNotLocalTime) {
+    // Pin the TZ to something far from UTC: the answer must not move. A server
+    // that changed hosts would otherwise silently reschedule everything.
+    const char* const old = getenv("TZ");
+    setenv("TZ", "Pacific/Kiritimati", 1); // UTC+14
+    tzset();
+    const CronExpr c = ok("0 0 * * *");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 7, 0, 0)));
+    EXPECT_FALSE(c.matches(utc(2026, 10, 7, 14, 0)));
+    EXPECT_EQ(c.nextFire(utc(2026, 10, 7, 0, 0)), utc(2026, 10, 8, 0, 0));
+    if (old != nullptr) {
+        setenv("TZ", old, 1);
+    } else {
+        unsetenv("TZ");
+    }
+    tzset();
+}
+
+// ------------------------------------------------- the dom/dow OR rule
+
+TEST(Cron, DomAndDowAreOredWhenBothRestricted) {
+    // "the 13th OR any Friday", not "Friday the 13th". The single most
+    // commonly got-wrong rule in cron.
+    const CronExpr c = ok("0 0 13 * FRI");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 13, 0, 0)));  // a Tuesday the 13th
+    EXPECT_TRUE(c.matches(utc(2026, 10, 9, 0, 0)));   // a Friday, not the 13th
+    EXPECT_TRUE(c.matches(utc(2026, 11, 13, 0, 0)));  // a Friday the 13th: both
+    EXPECT_FALSE(c.matches(utc(2026, 10, 14, 0, 0))); // neither
+}
+
+TEST(Cron, DomOnlyIsAndedWithAStarDow) {
+    const CronExpr c = ok("0 0 13 * *");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 13, 0, 0)));
+    EXPECT_FALSE(c.matches(utc(2026, 10, 9, 0, 0))); // a Friday must NOT fire
+}
+
+TEST(Cron, DowOnlyIsAndedWithAStarDom) {
+    const CronExpr c = ok("0 0 * * FRI");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 9, 0, 0)));
+    EXPECT_FALSE(c.matches(utc(2026, 10, 13, 0, 0))); // the 13th must NOT fire
+}
+
+TEST(Cron, OrRuleAlsoAppliesToRangesAndLists) {
+    const CronExpr c = ok("0 0 1,15 * MON-TUE");
+    EXPECT_TRUE(c.matches(utc(2026, 10, 1, 0, 0)));   // the 1st, a Thursday
+    EXPECT_TRUE(c.matches(utc(2026, 10, 15, 0, 0)));  // the 15th, a Thursday
+    EXPECT_TRUE(c.matches(utc(2026, 10, 5, 0, 0)));   // a Monday
+    EXPECT_TRUE(c.matches(utc(2026, 10, 6, 0, 0)));   // a Tuesday
+    EXPECT_FALSE(c.matches(utc(2026, 10, 7, 0, 0)));  // Wednesday the 7th
+    // The month field still ANDs, even under the OR rule: it is not a day field.
+    const CronExpr m = ok("0 0 13 7 FRI");
+    EXPECT_TRUE(m.matches(utc(2026, 7, 13, 0, 0)));
+    EXPECT_TRUE(m.matches(utc(2026, 7, 10, 0, 0)));   // a Friday in July
+    EXPECT_FALSE(m.matches(utc(2026, 8, 13, 0, 0)));  // the 13th, wrong month
+    EXPECT_FALSE(m.matches(utc(2026, 8, 14, 0, 0)));  // a Friday, wrong month
+}
+
+TEST(Cron, NextFireHonoursTheOrRule) {
+    const CronExpr c = ok("0 0 13 * FRI");
+    // From the 9th (a Friday) the next hit is the 13th, not the next Friday.
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 9, 0, 0)).value()), iso(utc(2026, 10, 13, 0, 0)));
+    // From the 13th the next hit is the following Friday, the 16th.
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 13, 0, 0)).value()), iso(utc(2026, 10, 16, 0, 0)));
+}
+
+// ----------------------------------------------------------------- nextFire
+
+TEST(Cron, NextFireIsStrictlyAfter) {
+    const CronExpr c = ok("* * * * *");
+    const std::time_t t = utc(2026, 10, 7, 13, 45);
+    EXPECT_EQ(c.nextFire(t), utc(2026, 10, 7, 13, 46));
+    // Mid-minute input rounds up to the next whole minute, never back to the
+    // minute it is already inside.
+    EXPECT_EQ(c.nextFire(utc(2026, 10, 7, 13, 45, 1)), utc(2026, 10, 7, 13, 46));
+    EXPECT_EQ(c.nextFire(utc(2026, 10, 7, 13, 45, 59)), utc(2026, 10, 7, 13, 46));
+}
+
+TEST(Cron, NextFireAlwaysLandsOnAWholeMinute) {
+    const std::time_t t = ok("*/7 * * * *").nextFire(utc(2026, 10, 7, 13, 45, 23)).value();
+    EXPECT_EQ(t % 60, 0);
+}
+
+TEST(Cron, NextFireCrossesAnHourBoundary) {
+    const CronExpr c = ok("5 * * * *");
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 13, 5)).value()), iso(utc(2026, 10, 7, 14, 5)));
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 13, 6)).value()), iso(utc(2026, 10, 7, 14, 5)));
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 13, 4)).value()), iso(utc(2026, 10, 7, 13, 5)));
+}
+
+TEST(Cron, NextFireCrossesADayBoundary) {
+    const CronExpr c = ok("30 2 * * *");
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 2, 30)).value()), iso(utc(2026, 10, 8, 2, 30)));
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 23, 59)).value()), iso(utc(2026, 10, 8, 2, 30)));
+}
+
+TEST(Cron, NextFireCrossesAMonthBoundary) {
+    const CronExpr c = ok("0 0 1 * *");
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 12, 0)).value()), iso(utc(2026, 11, 1, 0, 0)));
+    // 31-day months only: the engine must skip February, April and so on.
+    const CronExpr d = ok("0 0 31 * *");
+    EXPECT_EQ(iso(d.nextFire(utc(2026, 1, 31, 0, 1)).value()), iso(utc(2026, 3, 31, 0, 0)));
+}
+
+TEST(Cron, NextFireCrossesAYearBoundary) {
+    const CronExpr c = ok("0 0 1 1 *");
+    EXPECT_EQ(iso(c.nextFire(utc(2026, 10, 7, 12, 0)).value()), iso(utc(2027, 1, 1, 0, 0)));
+}
+
+TEST(Cron, NextFireFindsLeapDay) {
+    const CronExpr c = ok("0 12 29 2 *");
+    // 2028 is the next leap year, which is inside the one-year bound from 2027.
+    EXPECT_EQ(iso(c.nextFire(utc(2027, 3, 1, 0, 0)).value()), iso(utc(2028, 2, 29, 12, 0)));
+    EXPECT_EQ(iso(c.nextFire(utc(2028, 1, 1, 0, 0)).value()), iso(utc(2028, 2, 29, 12, 0)));
+    // Just after it fires, the following one is four years out - beyond the
+    // bound, so the answer is "nothing scheduled", not a hang.
+    EXPECT_FALSE(c.nextFire(utc(2028, 2, 29, 12, 0)).has_value());
+}
+
+TEST(Cron, NextFireReturnsNulloptForADateThatNeverExists) {
+    // Feb 30 parses - 30 is in range for day-of-month and 2 for month - and can
+    // never fire. Without the bound the search would spin forever.
+    EXPECT_FALSE(ok("0 0 30 2 *").nextFire(utc(2026, 1, 1, 0, 0)).has_value());
+    EXPECT_FALSE(ok("0 0 31 2 *").nextFire(utc(2026, 1, 1, 0, 0)).has_value());
+    // The OR rule rescues this one: Feb 30 never happens, but Monday does.
+    EXPECT_TRUE(ok("0 0 30 2 MON").nextFire(utc(2026, 1, 1, 0, 0)).has_value());
+}
+
+TEST(Cron, NextFireIsConsistentWithMatchesOverManyMinutes) {
+    // The cheap property test: whatever nextFire returns must match, nothing
+    // between the start and that answer may match, and iterating it must walk
+    // the schedule. Catches a whole class of off-by-one.
+    const std::vector<std::string> exprs = {
+        "* * * * *",      "*/7 * * * *",    "0 0 * * *",     "13 5 * * MON",
+        "0,30 9-17 * * 1-5", "59 23 31 12 *", "0 0 13 * FRI", "*/11 */3 1,15 1-6 *",
+        "45 */2 * * 0",   "0 4 29 2 *",
+    };
+    for (const std::string& e : exprs) {
+        const CronExpr c = ok(e);
+        std::time_t t = utc(2026, 2, 26, 22, 51); // near a month and a day boundary
+        for (int i = 0; i < 40; ++i) {
+            const std::optional<std::time_t> n = c.nextFire(t);
+            if (!n.has_value()) break; // a bounded expression legitimately runs out
+            ASSERT_GT(n.value(), t) << e;
+            EXPECT_EQ(n.value() % 60, 0) << e;
+            EXPECT_TRUE(c.matches(n.value())) << e << " at " << iso(n.value());
+            // Nothing in between may match, which is what "first" means. Both
+            // edges of the gap are scanned and the middle of a very long one is
+            // skipped, because an off-by-one lives at an edge, not in the middle.
+            const std::time_t edge = 4000 * 60;
+            for (std::time_t m = t + 60; m < n.value(); m += 60) {
+                if (m > t + edge && m < n.value() - edge) {
+                    m = n.value() - edge;
+                    continue;
+                }
+                ASSERT_FALSE(c.matches(m)) << e << " skipped " << iso(m);
+            }
+            t = n.value();
+        }
+    }
+}
+
+TEST(Cron, MatchesAndNextFireAgreeAcrossAFewHundredConsecutiveMinutes) {
+    // The other direction: walk real minutes and check that every matching one
+    // is reachable as the nextFire of the minute before it.
+    const std::vector<std::string> exprs = {"*/5 * * * *", "0 * * * *", "17 3 * * *",
+                                            "0 0 1,15 * SAT"};
+    for (const std::string& e : exprs) {
+        const CronExpr c = ok(e);
+        std::time_t t = utc(2026, 12, 31, 20, 0); // walk over a year boundary
+        for (int i = 0; i < 600; ++i, t += 60) {
+            if (!c.matches(t)) continue;
+            EXPECT_EQ(c.nextFire(t - 60), t) << e << " at " << iso(t);
+        }
+    }
+}
+
+// ------------------------------------------------------- zone-aware matching
+//
+// These need the host tz database, which is the one thing here that is not
+// pure. That is the point: the answers must come from tzdata, so a test that
+// faked it would prove nothing. Every expectation is a real transition written
+// out as a UTC instant, so a tzdata update that moves one fails here rather
+// than quietly moving somebody's schedule.
+
+TEST(CronZone, AnEmptyZoneIsByteIdenticalToTheUtcPath) {
+    // The compatibility guarantee: existing schedules carry no zone and must
+    // keep meaning exactly what they meant. Checked by walking both entry
+    // points over a few thousand consecutive minutes across a northern DST
+    // transition, where a leaked local-time assumption would show up.
+    const std::vector<std::string> exprs = {"* * * * *",   "*/7 * * * *",  "0 0 * * *",
+                                            "30 2 * * *",  "13 5 * * MON", "0 0 13 * FRI"};
+    for (const std::string& e : exprs) {
+        const CronExpr c = ok(e);
+        std::time_t t = utc(2026, 3, 28, 20, 0);
+        for (int i = 0; i < 4000; ++i, t += 60) {
+            ASSERT_EQ(c.matches(t), c.matchesIn(t, "")) << e << " at " << iso(t);
+        }
+        for (const std::time_t from : {utc(2026, 3, 28, 20, 0), utc(2026, 3, 29, 1, 30),
+                                       utc(2026, 10, 25, 0, 0), utc(2026, 12, 31, 23, 59)}) {
+            EXPECT_EQ(c.nextFire(from), c.nextFireIn(from, "")) << e << " from " << iso(from);
+        }
+    }
+}
+
+TEST(CronZone, AnUnknownZoneNeverFiresInsteadOfFallingBackToUtc) {
+    // A silent UTC fallback would move somebody's 08:00 report by an hour and
+    // look like it worked. The descriptor write path refuses an unknown zone,
+    // so reaching here means a row predates that check; never firing is the
+    // conservative answer, and the scheduler logs it.
+    const CronExpr c = ok("* * * * *");
+    EXPECT_FALSE(c.matchesIn(utc(2026, 7, 1, 12, 0), "Europe/Atlantis"));
+    EXPECT_FALSE(c.nextFireIn(utc(2026, 7, 1, 12, 0), "Europe/Atlantis").has_value());
+}
+
+TEST(CronZone, ADailyScheduleFiresAtLocalWallClockTime) {
+    // The bug this work exists for: 0 8 * * * with tz Europe/Budapest means
+    // 07:00 UTC in winter and 06:00 UTC in summer, not 08:00 UTC all year.
+    const CronExpr c = ok("0 8 * * *");
+    const std::string tz = "Europe/Budapest";
+
+    EXPECT_TRUE(c.matchesIn(utc(2026, 1, 15, 7, 0), tz));   // 08:00 CET
+    EXPECT_FALSE(c.matchesIn(utc(2026, 1, 15, 8, 0), tz));
+    EXPECT_TRUE(c.matchesIn(utc(2026, 7, 15, 6, 0), tz));   // 08:00 CEST
+    EXPECT_FALSE(c.matchesIn(utc(2026, 7, 15, 7, 0), tz));
+
+    EXPECT_EQ(c.nextFireIn(utc(2026, 1, 15, 0, 0), tz), utc(2026, 1, 15, 7, 0));
+    EXPECT_EQ(c.nextFireIn(utc(2026, 7, 15, 0, 0), tz), utc(2026, 7, 15, 6, 0));
+    // And it keeps meaning 08:00 local straight across the spring transition.
+    EXPECT_EQ(c.nextFireIn(utc(2026, 3, 28, 7, 0), tz), utc(2026, 3, 29, 6, 0));
+}
+
+TEST(CronZone, TheLocalDateDecidesTheDayFields) {
+    // 23:00 UTC is already the next day in Budapest, so a Monday-only schedule
+    // must fire on the Sunday-evening UTC instant that is Monday local.
+    const CronExpr c = ok("0 1 * * MON");
+    const std::string tz = "Europe/Budapest";
+    // 2026-07-06 is a Monday; 01:00 local is 23:00 UTC on Sunday the 5th.
+    EXPECT_TRUE(c.matchesIn(utc(2026, 7, 5, 23, 0), tz));
+    EXPECT_FALSE(c.matchesIn(utc(2026, 7, 6, 1, 0), tz));
+
+    // Same for day-of-month: the 1st local, not the 1st UTC.
+    const CronExpr d = ok("0 0 1 * *");
+    EXPECT_TRUE(d.matchesIn(utc(2026, 6, 30, 22, 0), tz)); // 2026-07-01 00:00 CEST
+    EXPECT_FALSE(d.matchesIn(utc(2026, 7, 1, 0, 0), tz));
+}
+
+TEST(CronZone, ANonHourOffsetIsRespectedToTheMinute) {
+    // Asia/Kathmandu is UTC+05:45. An implementation that assumed whole hours
+    // fires this 45 minutes off and passes every other test in this file.
+    const CronExpr c = ok("0 8 * * *");
+    const std::string tz = "Asia/Kathmandu";
+    EXPECT_TRUE(c.matchesIn(utc(2026, 6, 1, 2, 15), tz));
+    EXPECT_FALSE(c.matchesIn(utc(2026, 6, 1, 2, 0), tz));
+    EXPECT_FALSE(c.matchesIn(utc(2026, 6, 1, 3, 0), tz));
+    EXPECT_EQ(c.nextFireIn(utc(2026, 6, 1, 0, 0), tz), utc(2026, 6, 1, 2, 15));
+
+    // A minute-granular schedule in a :45 zone, to be sure the minute field is
+    // read from local wall clock and not from UTC.
+    const CronExpr m = ok("30 * * * *");
+    EXPECT_TRUE(m.matchesIn(utc(2026, 6, 1, 2, 45), tz)); // 08:30 local
+    EXPECT_FALSE(m.matchesIn(utc(2026, 6, 1, 2, 30), tz));
+}
+
+// ----------------------------------------------------------- the two DST cases
+
+TEST(CronZone, ASkippedLocalTimeStillFiresOnceAtTheEndOfTheGap) {
+    // Europe/Budapest 2026-03-29: 02:00 CET becomes 03:00 CEST at 01:00 UTC, so
+    // 02:30 local does not happen. Losing the run is the wrong answer - a
+    // nightly job that silently skips one night a year is a bug nobody finds.
+    const CronExpr c = ok("30 2 * * *");
+    const std::string tz = "Europe/Budapest";
+    const std::time_t gapEnd = utc(2026, 3, 29, 1, 0);
+
+    EXPECT_TRUE(c.matchesIn(gapEnd, tz));
+    // Once, and only at the gap end: no other minute that morning fires.
+    int fires = 0;
+    for (std::time_t t = utc(2026, 3, 28, 22, 0); t < utc(2026, 3, 29, 12, 0); t += 60)
+        if (c.matchesIn(t, tz)) ++fires;
+    EXPECT_EQ(fires, 1);
+
+    EXPECT_EQ(c.nextFireIn(utc(2026, 3, 28, 23, 0), tz), gapEnd);
+    // Having fired, the next one is the following day's real 02:30 CEST.
+    EXPECT_EQ(c.nextFireIn(gapEnd, tz), utc(2026, 3, 30, 0, 30));
+}
+
+TEST(CronZone, AWholeGapOfMatchingMinutesCollapsesToOneFire) {
+    // Every minute of the lost hour matches here. It must still be ONE run at
+    // the gap end, not sixty queued jobs.
+    const CronExpr c = ok("* 2 * * *");
+    const std::string tz = "Europe/Budapest";
+    const std::time_t gapEnd = utc(2026, 3, 29, 1, 0);
+
+    int fires = 0;
+    std::time_t only = 0;
+    for (std::time_t t = utc(2026, 3, 29, 0, 0); t < utc(2026, 3, 29, 2, 0); t += 60)
+        if (c.matchesIn(t, tz)) {
+            ++fires;
+            only = t;
+        }
+    EXPECT_EQ(fires, 1);
+    EXPECT_EQ(only, gapEnd);
+
+    EXPECT_EQ(c.nextFireIn(utc(2026, 3, 29, 0, 0), tz), gapEnd);
+    // And nothing more that day: 02:xx local never comes back.
+    EXPECT_EQ(c.nextFireIn(gapEnd, tz), utc(2026, 3, 30, 0, 0)); // 02:00 CEST next day
+}
+
+TEST(CronZone, ARepeatedLocalTimeFiresOnceNotTwice) {
+    // Europe/Budapest 2026-10-25: 03:00 CEST becomes 02:00 CET at 01:00 UTC, so
+    // 02:30 local happens at 00:30 UTC and again at 01:30 UTC. A daily job must
+    // run once that day.
+    const CronExpr c = ok("30 2 * * *");
+    const std::string tz = "Europe/Budapest";
+
+    EXPECT_TRUE(c.matchesIn(utc(2026, 10, 25, 0, 30), tz));  // first, CEST
+    EXPECT_FALSE(c.matchesIn(utc(2026, 10, 25, 1, 30), tz)); // second, CET: not again
+
+    int fires = 0;
+    for (std::time_t t = utc(2026, 10, 24, 22, 0); t < utc(2026, 10, 25, 12, 0); t += 60)
+        if (c.matchesIn(t, tz)) ++fires;
+    EXPECT_EQ(fires, 1);
+
+    EXPECT_EQ(c.nextFireIn(utc(2026, 10, 25, 0, 0), tz), utc(2026, 10, 25, 0, 30));
+    EXPECT_EQ(c.nextFireIn(utc(2026, 10, 25, 0, 30), tz), utc(2026, 10, 26, 1, 30));
+}
+
+TEST(CronZone, TheRepeatedHourDoesNotRunTwiceForAnHourlySchedule) {
+    // An hourly job over the fold: 24 runs that day, not 25. The repeated wall
+    // clock hour is counted once, which is what "once per wall-clock hour"
+    // means and the position the time zone seam commits to.
+    const CronExpr c = ok("0 * * * *");
+    const std::string tz = "Europe/Budapest";
+    int fires = 0;
+    // The whole local day 2026-10-25 runs from 22:00 UTC on the 24th to 23:00
+    // UTC on the 25th, 25 hours of real time.
+    for (std::time_t t = utc(2026, 10, 24, 22, 0); t < utc(2026, 10, 25, 23, 0); t += 60)
+        if (c.matchesIn(t, tz)) ++fires;
+    EXPECT_EQ(fires, 24); // 00:00 through 23:00 local, each once
+}
+
+TEST(CronZone, SouthernHemisphereTransitionsRunTheOtherWay) {
+    // Australia/Sydney gains an hour in October and loses it in April, the
+    // reverse of Europe. A hard-coded northern rule gets both of these wrong.
+    const CronExpr c = ok("30 2 * * *");
+    const std::string tz = "Australia/Sydney";
+
+    // 2026-10-04: 02:00 AEST becomes 03:00 AEDT at 16:00 UTC on the 3rd.
+    const std::time_t gapEnd = utc(2026, 10, 3, 16, 0);
+    EXPECT_TRUE(c.matchesIn(gapEnd, tz));
+    EXPECT_EQ(c.nextFireIn(utc(2026, 10, 3, 14, 0), tz), gapEnd);
+    int springFires = 0;
+    for (std::time_t t = utc(2026, 10, 3, 12, 0); t < utc(2026, 10, 4, 12, 0); t += 60)
+        if (c.matchesIn(t, tz)) ++springFires;
+    EXPECT_EQ(springFires, 1);
+
+    // 2026-04-05: 03:00 AEDT becomes 02:00 AEST at 16:00 UTC on the 4th, so
+    // 02:30 local happens at 15:30 and again at 16:30 UTC.
+    EXPECT_TRUE(c.matchesIn(utc(2026, 4, 4, 15, 30), tz));
+    EXPECT_FALSE(c.matchesIn(utc(2026, 4, 4, 16, 30), tz));
+    int autumnFires = 0;
+    for (std::time_t t = utc(2026, 4, 4, 12, 0); t < utc(2026, 4, 5, 12, 0); t += 60)
+        if (c.matchesIn(t, tz)) ++autumnFires;
+    EXPECT_EQ(autumnFires, 1);
+}
+
+TEST(CronZone, ADailyScheduleFiresExactlyOncePerLocalDayAcrossBothTransitions) {
+    // The end-to-end statement of the whole feature: whatever the zone and
+    // whatever the transition, a daily schedule runs once a local day. Counted
+    // over the weeks containing each transition in both hemispheres, with the
+    // schedule set to the hour the transitions actually touch.
+    struct Case {
+        const char* zone;
+        int year;
+        int month;
+        int day;
+    };
+    for (const Case& k : {Case{"Europe/Budapest", 2026, 3, 26},
+                          Case{"Europe/Budapest", 2026, 10, 22},
+                          Case{"Australia/Sydney", 2026, 10, 1},
+                          Case{"Australia/Sydney", 2026, 4, 2},
+                          Case{"Asia/Kathmandu", 2026, 3, 26}}) {
+        const CronExpr c = ok("30 2 * * *");
+        // The window is seven local days, found through nextFireIn so the
+        // counting cannot be fooled by the hour the transition adds or removes.
+        std::optional<std::time_t> t = c.nextFireIn(utc(k.year, k.month, k.day, 0, 0), k.zone);
+        int fires = 0;
+        std::time_t last = 0;
+        for (int i = 0; i < 7 && t.has_value(); ++i) {
+            ++fires;
+            last = t.value();
+            t = c.nextFireIn(last, k.zone);
+        }
+        EXPECT_EQ(fires, 7) << k.zone;
+        // Seven fires span six days of local time, give or take the DST hour.
+        const std::time_t first =
+            c.nextFireIn(utc(k.year, k.month, k.day, 0, 0), k.zone).value_or(0);
+        EXPECT_GE(last - first, 6 * 24 * 3600 - 3600) << k.zone;
+        EXPECT_LE(last - first, 6 * 24 * 3600 + 3600) << k.zone;
+    }
+}
+
+TEST(CronZone, NextFireAlwaysMatchesInTheSameZone) {
+    // The property test. Whatever nextFireIn returns must matchIn, nothing
+    // between may matchIn, and iterating it must walk the schedule. Run across
+    // both transitions in several zones, including one with a :45 offset and
+    // the empty (UTC) zone.
+    const std::vector<std::string> zones = {"Europe/Budapest", "Australia/Sydney",
+                                            "Asia/Kathmandu", "UTC", ""};
+    const std::vector<std::string> exprs = {"* * * * *",     "*/7 * * * *", "30 2 * * *",
+                                            "0 8 * * *",     "0,30 9-17 * * 1-5",
+                                            "59 23 31 12 *", "0 0 13 * FRI", "45 */2 * * 0"};
+    const std::vector<std::time_t> starts = {utc(2026, 3, 28, 23, 0), utc(2026, 10, 24, 23, 0),
+                                             utc(2026, 4, 4, 14, 0), utc(2026, 10, 3, 14, 0)};
+    for (const std::string& z : zones) {
+        for (const std::string& e : exprs) {
+            const CronExpr c = ok(e);
+            for (const std::time_t start : starts) {
+                std::time_t t = start;
+                for (int i = 0; i < 20; ++i) {
+                    const std::optional<std::time_t> n = c.nextFireIn(t, z);
+                    if (!n.has_value()) break;
+                    ASSERT_GT(n.value(), t) << e << " in '" << z << "'";
+                    ASSERT_EQ(n.value() % 60, 0) << e << " in '" << z << "'";
+                    ASSERT_TRUE(c.matchesIn(n.value(), z))
+                        << e << " in '" << z << "' at " << iso(n.value());
+                    // Nothing in between may match, which is what "first"
+                    // means. Only walked when the gap is short enough to walk;
+                    // a yearly schedule's gap is covered by the cases above.
+                    if (n.value() - t <= 3 * 24 * 3600) {
+                        for (std::time_t m = t + 60; m < n.value(); m += 60)
+                            ASSERT_FALSE(c.matchesIn(m, z))
+                                << e << " in '" << z << "' skipped " << iso(m);
+                    }
+                    t = n.value();
+                }
+            }
+        }
+    }
+}
+
+TEST(CronZone, NextFireReturnsNulloptForADateThatNeverExistsInAZoneToo) {
+    // The bound that stops a legal but impossible expression from spinning has
+    // to hold in the local-calendar walk as well.
+    EXPECT_FALSE(
+        ok("0 0 30 2 *").nextFireIn(utc(2026, 1, 1, 0, 0), "Europe/Budapest").has_value());
+    EXPECT_FALSE(
+        ok("0 0 31 2 *").nextFireIn(utc(2026, 1, 1, 0, 0), "Australia/Sydney").has_value());
+    // But a leap day is found, in local time, within the bound.
+    const std::optional<std::time_t> leap =
+        ok("0 4 29 2 *").nextFireIn(utc(2027, 3, 1, 0, 0), "Europe/Budapest");
+    ASSERT_TRUE(leap.has_value());
+    EXPECT_EQ(leap.value(), utc(2028, 2, 29, 3, 0)); // 04:00 CET
+}

+ 252 - 0
tests/test_functions_timezone.cpp

@@ -0,0 +1,252 @@
+// Unit tests for the IANA time zone seam.
+//
+// Pure apart from the host tz database, which is the one external thing these
+// cannot fake: the whole point of the seam is that the answers come from
+// tzdata, so a test that stubbed it would prove nothing. Every expectation
+// below is a real historical or scheduled transition, written out as a UTC
+// instant, so a tzdata update that moved a transition fails loudly here instead
+// of quietly moving somebody's schedule.
+#include <gtest/gtest.h>
+
+#include <ctime>
+#include <string>
+
+#include "functions/timezone.hpp"
+
+using svapi::functions::LocalInstant;
+using svapi::functions::timezoneKnown;
+using svapi::functions::utcFromLocal;
+using svapi::functions::ZoneParts;
+using svapi::functions::zonePartsAt;
+
+namespace {
+
+std::time_t utc(int year, int mon, int day, int hour, int min, int sec = 0) {
+    std::tm tm{};
+    tm.tm_year = year - 1900;
+    tm.tm_mon = mon - 1;
+    tm.tm_mday = day;
+    tm.tm_hour = hour;
+    tm.tm_min = min;
+    tm.tm_sec = sec;
+    return timegm(&tm);
+}
+
+} // namespace
+
+// ----------------------------------------------------------------- known
+
+TEST(Timezone, KnowsRealZones) {
+    EXPECT_TRUE(timezoneKnown("UTC"));
+    EXPECT_TRUE(timezoneKnown("Europe/Budapest"));
+    EXPECT_TRUE(timezoneKnown("Australia/Sydney"));
+    EXPECT_TRUE(timezoneKnown("Asia/Kathmandu"));
+    EXPECT_TRUE(timezoneKnown("America/New_York"));
+}
+
+TEST(Timezone, RejectsNonZonesRatherThanFallingBackToUtc) {
+    // The whole reason the API is optional: an unknown zone must be an answer
+    // of "no", never a silent UTC that looks like it worked.
+    EXPECT_FALSE(timezoneKnown(""));
+    EXPECT_FALSE(timezoneKnown("Europe/Atlantis"));
+    EXPECT_FALSE(timezoneKnown("CEST"));
+    EXPECT_FALSE(timezoneKnown("+02:00"));
+    EXPECT_FALSE(timezoneKnown("europe/budapest")); // zone names are case sensitive
+    EXPECT_FALSE(timezoneKnown("../../etc/passwd"));
+}
+
+TEST(Timezone, PartsAndLocalBothDeclineAnUnknownZone) {
+    EXPECT_FALSE(zonePartsAt("Europe/Atlantis", utc(2026, 7, 1, 12, 0)).has_value());
+    EXPECT_FALSE(utcFromLocal("Europe/Atlantis", 2026, 7, 1, 12, 0, 0).has_value());
+    EXPECT_FALSE(zonePartsAt("", utc(2026, 7, 1, 12, 0)).has_value());
+    EXPECT_FALSE(utcFromLocal("", 2026, 7, 1, 12, 0, 0).has_value());
+}
+
+// ----------------------------------------------------------------- parts
+
+TEST(Timezone, PartsInSummerAndWinter) {
+    const std::optional<ZoneParts> summer =
+        zonePartsAt("Europe/Budapest", utc(2026, 7, 1, 10, 0));
+    ASSERT_TRUE(summer.has_value());
+    EXPECT_EQ(summer->year, 2026);
+    EXPECT_EQ(summer->month, 7);
+    EXPECT_EQ(summer->day, 1);
+    EXPECT_EQ(summer->hour, 12); // UTC+2
+    EXPECT_EQ(summer->minute, 0);
+    EXPECT_EQ(summer->offsetSec, 7200);
+    EXPECT_TRUE(summer->dst);
+    EXPECT_EQ(summer->abbrev, "CEST");
+
+    const std::optional<ZoneParts> winter =
+        zonePartsAt("Europe/Budapest", utc(2026, 1, 15, 10, 0));
+    ASSERT_TRUE(winter.has_value());
+    EXPECT_EQ(winter->hour, 11); // UTC+1
+    EXPECT_EQ(winter->offsetSec, 3600);
+    EXPECT_FALSE(winter->dst);
+    EXPECT_EQ(winter->abbrev, "CET");
+}
+
+TEST(Timezone, PartsCarryWeekdayAndYearday) {
+    // 2026-01-01 is a Thursday.
+    const std::optional<ZoneParts> p = zonePartsAt("UTC", utc(2026, 1, 1, 0, 0));
+    ASSERT_TRUE(p.has_value());
+    EXPECT_EQ(p->weekday, 4); // 0 = Sunday, matching cron
+    EXPECT_EQ(p->yearday, 1);
+
+    // 2026-10-07 is a Wednesday, day 280 of the year.
+    const std::optional<ZoneParts> q = zonePartsAt("UTC", utc(2026, 10, 7, 0, 0));
+    ASSERT_TRUE(q.has_value());
+    EXPECT_EQ(q->weekday, 3);
+    EXPECT_EQ(q->yearday, 280);
+}
+
+TEST(Timezone, PartsCrossTheLocalDateLineNotTheUtcOne) {
+    // 23:30 UTC is already the next day in Budapest. A scheduler that read UTC
+    // parts here would run a "daily" job on the wrong date.
+    const std::optional<ZoneParts> p =
+        zonePartsAt("Europe/Budapest", utc(2026, 7, 1, 23, 30));
+    ASSERT_TRUE(p.has_value());
+    EXPECT_EQ(p->day, 2);
+    EXPECT_EQ(p->hour, 1);
+    EXPECT_EQ(p->weekday, 4); // 2026-07-02 is a Thursday
+}
+
+TEST(Timezone, PartsHandleANonHourOffset) {
+    // Kathmandu is UTC+05:45. An implementation that assumed whole hours gets
+    // the minute field wrong here and nowhere else.
+    const std::optional<ZoneParts> p = zonePartsAt("Asia/Kathmandu", utc(2026, 6, 1, 2, 15));
+    ASSERT_TRUE(p.has_value());
+    EXPECT_EQ(p->hour, 8);
+    EXPECT_EQ(p->minute, 0);
+    EXPECT_EQ(p->offsetSec, 20700);
+    EXPECT_FALSE(p->dst);
+}
+
+TEST(Timezone, UtcZoneIsTheIdentity) {
+    const std::time_t t = utc(2026, 5, 17, 13, 44, 9);
+    const std::optional<ZoneParts> p = zonePartsAt("UTC", t);
+    ASSERT_TRUE(p.has_value());
+    EXPECT_EQ(p->hour, 13);
+    EXPECT_EQ(p->minute, 44);
+    EXPECT_EQ(p->second, 9);
+    EXPECT_EQ(p->offsetSec, 0);
+}
+
+// ------------------------------------------------------------ utcFromLocal
+
+TEST(Timezone, LocalToUtcRoundTrips) {
+    const std::optional<LocalInstant> li =
+        utcFromLocal("Europe/Budapest", 2026, 7, 1, 12, 0, 0);
+    ASSERT_TRUE(li.has_value());
+    EXPECT_EQ(li->utc, utc(2026, 7, 1, 10, 0));
+    EXPECT_TRUE(li->existed);
+    EXPECT_FALSE(li->ambiguous);
+
+    const std::optional<LocalInstant> kt =
+        utcFromLocal("Asia/Kathmandu", 2026, 6, 1, 8, 0, 0);
+    ASSERT_TRUE(kt.has_value());
+    EXPECT_EQ(kt->utc, utc(2026, 6, 1, 2, 15));
+}
+
+TEST(Timezone, LocalToUtcRejectsADateThatDoesNotExist) {
+    EXPECT_FALSE(utcFromLocal("UTC", 2026, 2, 30, 12, 0, 0).has_value());
+    EXPECT_FALSE(utcFromLocal("UTC", 2026, 13, 1, 12, 0, 0).has_value());
+    EXPECT_FALSE(utcFromLocal("UTC", 2026, 0, 1, 12, 0, 0).has_value());
+    EXPECT_FALSE(utcFromLocal("UTC", 2026, 4, 31, 12, 0, 0).has_value());
+    // 2026 is not a leap year; 2024 was.
+    EXPECT_FALSE(utcFromLocal("UTC", 2026, 2, 29, 12, 0, 0).has_value());
+    EXPECT_TRUE(utcFromLocal("UTC", 2024, 2, 29, 12, 0, 0).has_value());
+}
+
+TEST(Timezone, ASkippedLocalTimeReportsTheEndOfTheGap) {
+    // Europe/Budapest, 2026-03-29: 02:00 CET becomes 03:00 CEST at 01:00 UTC.
+    // 02:30 local never happens that morning.
+    const std::optional<LocalInstant> li =
+        utcFromLocal("Europe/Budapest", 2026, 3, 29, 2, 30, 0);
+    ASSERT_TRUE(li.has_value());
+    EXPECT_FALSE(li->existed);
+    EXPECT_FALSE(li->ambiguous);
+    // The instant the gap ends, which is 03:00 local. A schedule lands once
+    // there rather than being lost.
+    EXPECT_EQ(li->utc, utc(2026, 3, 29, 1, 0));
+
+    // Every minute in the gap collapses onto the same instant, which is exactly
+    // what makes the schedule fire once and not sixty times.
+    for (int m = 0; m < 60; ++m) {
+        const std::optional<LocalInstant> g =
+            utcFromLocal("Europe/Budapest", 2026, 3, 29, 2, m, 0);
+        ASSERT_TRUE(g.has_value()) << m;
+        EXPECT_FALSE(g->existed) << m;
+        EXPECT_EQ(g->utc, utc(2026, 3, 29, 1, 0)) << m;
+    }
+
+    // Either side of the gap is ordinary.
+    const std::optional<LocalInstant> before =
+        utcFromLocal("Europe/Budapest", 2026, 3, 29, 1, 59, 0);
+    ASSERT_TRUE(before.has_value());
+    EXPECT_TRUE(before->existed);
+    EXPECT_EQ(before->utc, utc(2026, 3, 29, 0, 59));
+
+    const std::optional<LocalInstant> after =
+        utcFromLocal("Europe/Budapest", 2026, 3, 29, 3, 0, 0);
+    ASSERT_TRUE(after.has_value());
+    EXPECT_TRUE(after->existed);
+    EXPECT_EQ(after->utc, utc(2026, 3, 29, 1, 0));
+}
+
+TEST(Timezone, ARepeatedLocalTimeReportsTheFirstOccurrence) {
+    // Europe/Budapest, 2026-10-25: 03:00 CEST becomes 02:00 CET at 01:00 UTC.
+    // 02:30 local happens twice, at 00:30 UTC and again at 01:30 UTC.
+    const std::optional<LocalInstant> li =
+        utcFromLocal("Europe/Budapest", 2026, 10, 25, 2, 30, 0);
+    ASSERT_TRUE(li.has_value());
+    EXPECT_TRUE(li->existed);
+    EXPECT_TRUE(li->ambiguous);
+    EXPECT_EQ(li->utc, utc(2026, 10, 25, 0, 30)); // the first one, in CEST
+}
+
+TEST(Timezone, SouthernHemisphereTransitionsRunTheOtherWay) {
+    // Australia/Sydney gains an hour in October and loses it in April, the
+    // reverse of Europe. A hard-coded northern rule gets both of these wrong.
+    const std::optional<LocalInstant> gap =
+        utcFromLocal("Australia/Sydney", 2026, 10, 4, 2, 30, 0);
+    ASSERT_TRUE(gap.has_value());
+    EXPECT_FALSE(gap->existed);
+    EXPECT_EQ(gap->utc, utc(2026, 10, 3, 16, 0)); // 03:00 AEDT
+
+    const std::optional<LocalInstant> fold =
+        utcFromLocal("Australia/Sydney", 2026, 4, 5, 2, 30, 0);
+    ASSERT_TRUE(fold.has_value());
+    EXPECT_TRUE(fold->existed);
+    EXPECT_TRUE(fold->ambiguous);
+    EXPECT_EQ(fold->utc, utc(2026, 4, 4, 15, 30)); // the first one, in AEDT
+
+    // And the abbreviations are the other way round too.
+    const std::optional<ZoneParts> jan = zonePartsAt("Australia/Sydney", utc(2026, 1, 15, 0, 0));
+    ASSERT_TRUE(jan.has_value());
+    EXPECT_TRUE(jan->dst);
+    EXPECT_EQ(jan->offsetSec, 39600);
+    const std::optional<ZoneParts> jul = zonePartsAt("Australia/Sydney", utc(2026, 7, 15, 0, 0));
+    ASSERT_TRUE(jul.has_value());
+    EXPECT_FALSE(jul->dst);
+    EXPECT_EQ(jul->offsetSec, 36000);
+}
+
+TEST(Timezone, PartsOfALocalInstantAreThatLocalTimeAgain) {
+    // The property that matters to a scheduler: for an unambiguous wall-clock
+    // time, parts(utcFromLocal(L)) == L. Walked over a month of local noons in
+    // two zones so a transition is included.
+    for (const std::string zone : {"Europe/Budapest", "Australia/Sydney", "Asia/Kathmandu"}) {
+        for (int day = 1; day <= 31; ++day) {
+            const std::optional<LocalInstant> li = utcFromLocal(zone, 2026, 3, day, 12, 0, 0);
+            ASSERT_TRUE(li.has_value()) << zone << " day " << day;
+            const std::optional<ZoneParts> p = zonePartsAt(zone, li->utc);
+            ASSERT_TRUE(p.has_value());
+            EXPECT_EQ(p->year, 2026) << zone << " day " << day;
+            EXPECT_EQ(p->month, 3) << zone << " day " << day;
+            EXPECT_EQ(p->day, day) << zone << " day " << day;
+            EXPECT_EQ(p->hour, 12) << zone << " day " << day;
+            EXPECT_EQ(p->minute, 0) << zone << " day " << day;
+        }
+    }
+}

+ 192 - 0
tests/test_project_secret_store.cpp

@@ -0,0 +1,192 @@
+// ProjectSecretStore against a fake database.
+//
+// Same link-time fake as test_function_run_log.cpp: this file defines the
+// handful of `smartbotic::database::Client` members the store calls, so the
+// target never links the real client and still builds where
+// libsmartbotic-db-client cannot be linked at all.
+//
+// Every stub ignores `this` and works on the file-static `g_db` below, so no
+// Client or DbGateway object is ever constructed or read.
+#include "project_secret_store.hpp"
+#include <gtest/gtest.h>
+#include <map>
+#include <set>
+
+using nlohmann::json;
+using Client = smartbotic::database::Client;
+
+namespace {
+
+/// collection -> document id -> body.
+std::map<std::string, std::map<std::string, json>> g_db;
+std::map<std::string, bool> g_created;
+/// Collections created with the encrypted flag set. The flag is fixed at
+/// creation, so "was it created encrypted" is the only question worth asking.
+std::set<std::string> g_encrypted;
+
+void resetDb() { g_db.clear(); g_created.clear(); g_encrypted.clear(); }
+
+}  // namespace
+
+namespace smartbotic::database {
+
+bool Client::createCollection(const std::string& name, uint32_t, bool encrypted, uint32_t,
+                              uint32_t) {
+    g_created[name] = true;
+    if (encrypted) g_encrypted.insert(name);
+    g_db[name];
+    return true;
+}
+
+std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
+    if (!g_created.count(name)) return std::nullopt;
+    CollectionInfo info;
+    info.name = name;
+    info.documentCount = g_db[name].size();
+    return info;
+}
+
+bool Client::dropCollection(const std::string& name) {
+    g_created.erase(name);
+    g_encrypted.erase(name);
+    return g_db.erase(name) > 0;
+}
+
+std::pair<std::string, bool> Client::upsert(const std::string& collection, const json& data,
+                                            const std::string& id, uint32_t, const std::string&) {
+    const bool isNew = g_db[collection].count(id) == 0;
+    json body = data;
+    body.erase("id");  // the real client strips a top-level `id` from the body
+    g_db[collection][id] = std::move(body);
+    return {id, isNew};
+}
+
+std::optional<json> Client::get(const std::string& collection, const std::string& id) {
+    auto c = g_db.find(collection);
+    if (c == g_db.end()) return std::nullopt;
+    auto d = c->second.find(id);
+    if (d == c->second.end()) return std::nullopt;
+    return d->second;
+}
+
+bool Client::exists(const std::string& collection, const std::string& id) {
+    return g_db.count(collection) && g_db[collection].count(id);
+}
+
+bool Client::remove(const std::string& collection, const std::string& id) {
+    return g_db[collection].erase(id) > 0;
+}
+
+std::vector<json> Client::find(const std::string& collection, const QueryOptions& options) {
+    std::vector<json> page;
+    for (const auto& [id, body] : g_db[collection]) {
+        if (page.size() >= options.limit) break;
+        page.push_back(body);
+    }
+    return page;
+}
+
+}  // namespace smartbotic::database
+
+namespace svapi {
+
+/// Mirrors db_gateway.cpp, which cannot be linked here: it constructs a real
+/// Client, whose PIMPL lives in the library this target exists to avoid.
+std::string qualify(const std::string& project, const std::string& collection) {
+    if (project.empty() || project == "default") return collection;
+    return project + ":" + collection;
+}
+
+Client& DbGateway::client() {
+    alignas(Client) static unsigned char storage[sizeof(void*) * 4];
+    return *reinterpret_cast<Client*>(storage);
+}
+
+}  // namespace svapi
+
+namespace {
+
+/// A DbGateway reference whose object is never touched: every call reaching it
+/// lands in a stub above.
+svapi::DbGateway& fakeGateway() {
+    alignas(svapi::DbGateway) static unsigned char storage[sizeof(void*) * 8];
+    return *reinterpret_cast<svapi::DbGateway*>(storage);
+}
+
+class SecretStoreTest : public ::testing::Test {
+protected:
+    void SetUp() override { resetDb(); }
+    svapi::ProjectSecretStore store{fakeGateway()};
+};
+
+TEST_F(SecretStoreTest, StoresPerProjectInAQualifiedEncryptedCollection) {
+    bool created = false;
+    store.put("acme", "BOT_TOKEN", "xoxb-1", created);
+    EXPECT_TRUE(created);
+    EXPECT_TRUE(g_db.count("acme:vectorapi_secrets")) << "the collection must be project-scoped";
+    EXPECT_TRUE(g_encrypted.count("acme:vectorapi_secrets")) << "secrets must be encrypted at rest";
+    // The id is the name, and the name is in the body too, because the client
+    // strips a top-level `id` from stored bodies.
+    EXPECT_EQ(g_db["acme:vectorapi_secrets"]["BOT_TOKEN"]["name"], "BOT_TOKEN");
+}
+
+TEST_F(SecretStoreTest, OneProjectsSecretsAreInvisibleToAnother) {
+    bool created = false;
+    store.put("acme", "BOT_TOKEN", "acme-value", created);
+    store.put("novitax", "BOT_TOKEN", "novitax-value", created);
+
+    EXPECT_EQ(store.get("acme", "BOT_TOKEN")->value, "acme-value");
+    EXPECT_EQ(store.get("novitax", "BOT_TOKEN")->value, "novitax-value");
+    EXPECT_EQ(store.valuesFor("acme").size(), 1u);
+    EXPECT_EQ(store.valuesFor("acme").at("BOT_TOKEN"), "acme-value");
+}
+
+TEST_F(SecretStoreTest, ARotationKeepsCreatedAtAndIsNotReportedAsNew) {
+    bool created = false;
+    const svapi::ProjectSecret first = store.put("acme", "BOT_TOKEN", "v1", created);
+    ASSERT_TRUE(created);
+
+    const svapi::ProjectSecret second = store.put("acme", "BOT_TOKEN", "v2", created);
+    EXPECT_FALSE(created);
+    EXPECT_EQ(second.value, "v2");
+    EXPECT_EQ(second.createdAt, first.createdAt);
+    EXPECT_GE(second.updatedAt, first.updatedAt);
+    EXPECT_EQ(store.list("acme").size(), 1u) << "a rotation must not create a second row";
+}
+
+TEST_F(SecretStoreTest, RemoveReportsWhetherThereWasAnythingToRemove) {
+    bool created = false;
+    store.put("acme", "BOT_TOKEN", "v1", created);
+    EXPECT_TRUE(store.remove("acme", "BOT_TOKEN"));
+    EXPECT_FALSE(store.remove("acme", "BOT_TOKEN"));
+    EXPECT_FALSE(store.remove("acme", "NEVER_SET"));
+    EXPECT_TRUE(store.valuesFor("acme").empty());
+}
+
+TEST_F(SecretStoreTest, ReadingAProjectWithNoSecretsIsEmptyNotAnError) {
+    EXPECT_TRUE(store.list("fresh").empty());
+    EXPECT_TRUE(store.valuesFor("fresh").empty());
+    EXPECT_FALSE(store.get("fresh", "BOT_TOKEN").has_value());
+}
+
+TEST_F(SecretStoreTest, ValuesForSkipsARowWhoseNameBreaksTheRule) {
+    // Such a row cannot come from the API; it would be hand-written straight
+    // into the collection, and it must not reach ctx.env under that spelling.
+    g_created["acme:vectorapi_secrets"] = true;
+    g_db["acme:vectorapi_secrets"]["__proto__"] = json{{"name", "__proto__"}, {"value", "x"}};
+    g_db["acme:vectorapi_secrets"]["GOOD"] = json{{"name", "GOOD"}, {"value", "keep"}};
+
+    const std::map<std::string, std::string> values = store.valuesFor("acme");
+    EXPECT_EQ(values.size(), 1u);
+    EXPECT_EQ(values.at("GOOD"), "keep");
+}
+
+TEST_F(SecretStoreTest, DropAllRemovesEverythingSoARecycledProjectNameInheritsNothing) {
+    bool created = false;
+    store.put("acme", "BOT_TOKEN", "v1", created);
+    store.dropAll("acme");
+    EXPECT_FALSE(g_db.count("acme:vectorapi_secrets"));
+    EXPECT_TRUE(store.valuesFor("acme").empty());
+}
+
+}  // namespace

+ 94 - 0
tests/test_project_secrets.cpp

@@ -0,0 +1,94 @@
+// The pure half of per-project function secrets: the name rule, and the fact
+// that the API view of a secret cannot carry its value.
+//
+// No database client here, so this target builds and runs on a host where the
+// client cannot compile.
+#include <gtest/gtest.h>
+
+#include "project_secrets.hpp"
+
+using svapi::kMaxSecretNameLength;
+using svapi::ProjectSecret;
+using svapi::validSecretName;
+
+TEST(SecretName, AcceptsEnvironmentVariableStyleIdentifiers) {
+    EXPECT_TRUE(validSecretName("BOT_TOKEN"));
+    EXPECT_TRUE(validSecretName("A"));
+    EXPECT_TRUE(validSecretName("_PRIVATE"));
+    EXPECT_TRUE(validSecretName("OPENAI_KEY_2"));
+    EXPECT_TRUE(validSecretName("MY__NESTED_NAME"));
+    EXPECT_TRUE(validSecretName(std::string(kMaxSecretNameLength, 'X')));
+}
+
+TEST(SecretName, RejectsLowerCase) {
+    // Two names differing only in case would be two secrets that look like one,
+    // and the host variables this merges with are upper case by convention.
+    EXPECT_FALSE(validSecretName("bot_token"));
+    EXPECT_FALSE(validSecretName("Bot_Token"));
+}
+
+TEST(SecretName, RejectsAnythingTheEnvironmentCannotCarry) {
+    EXPECT_FALSE(validSecretName("HAS-DASH"));
+    EXPECT_FALSE(validSecretName("HAS.DOT"));
+    EXPECT_FALSE(validSecretName("HAS:COLON"));   // the qualify() separator
+    EXPECT_FALSE(validSecretName("HAS SPACE"));
+    EXPECT_FALSE(validSecretName("HAS/SLASH"));
+    EXPECT_FALSE(validSecretName(".."));          // never a path segment either
+    EXPECT_FALSE(validSecretName("UTF8_\xc3\xa9"));
+}
+
+TEST(SecretName, RejectsEmptyTooLongAndALeadingDigit) {
+    EXPECT_FALSE(validSecretName(""));
+    EXPECT_FALSE(validSecretName(std::string(kMaxSecretNameLength + 1, 'X')));
+    EXPECT_FALSE(validSecretName("9LIVES"));
+    EXPECT_FALSE(validSecretName("0"));
+}
+
+TEST(Secret, StoredFormRoundTrips) {
+    ProjectSecret s;
+    s.name      = "BOT_TOKEN";
+    s.value     = "xoxb-super-secret";
+    s.createdAt = 1700000000;
+    s.updatedAt = 1700000500;
+
+    const ProjectSecret back = ProjectSecret::fromJson(s.toJson());
+    EXPECT_EQ(back.name, s.name);
+    EXPECT_EQ(back.value, s.value);
+    EXPECT_EQ(back.createdAt, s.createdAt);
+    EXPECT_EQ(back.updatedAt, s.updatedAt);
+}
+
+TEST(Secret, FromJsonToleratesAMissingOrOddDocument) {
+    const ProjectSecret empty = ProjectSecret::fromJson(nlohmann::json::object());
+    EXPECT_TRUE(empty.name.empty());
+    EXPECT_TRUE(empty.value.empty());
+    EXPECT_EQ(empty.createdAt, 0u);
+    EXPECT_EQ(empty.updatedAt, 0u);
+}
+
+TEST(Secret, TheApiViewNeverCarriesTheValue) {
+    // The property the whole feature rests on: no GET may return a value, not
+    // masked, not truncated, and not as a length that narrows a guess.
+    ProjectSecret s;
+    s.name      = "BOT_TOKEN";
+    s.value     = "xoxb-super-secret";
+    s.createdAt = 1700000000;
+    s.updatedAt = 1700000500;
+
+    const nlohmann::json view = s.summaryJson();
+    EXPECT_EQ(view.at("name"), "BOT_TOKEN");
+    EXPECT_EQ(view.at("set"), true);
+    EXPECT_EQ(view.at("created_at"), 1700000000);
+    EXPECT_EQ(view.at("updated_at"), 1700000500);
+    EXPECT_FALSE(view.contains("value"));
+    EXPECT_EQ(view.size(), 4u) << "a new field was added to the secret view - is it safe?";
+    EXPECT_EQ(view.dump().find("xoxb"), std::string::npos) << "the value leaked into the view";
+}
+
+TEST(Secret, SetIsFalseOnlyWhenNoValueIsStored) {
+    ProjectSecret s;
+    s.name = "EMPTY";
+    EXPECT_EQ(s.summaryJson().at("set"), false);
+    s.value = "x";
+    EXPECT_EQ(s.summaryJson().at("set"), true);
+}

+ 46 - 0
tests/test_project_settings.cpp

@@ -189,3 +189,49 @@ TEST(ProjectSettings, AnUnsetPolicyIsNotWrittenToStorage) {
     const ProjectSettings p;
     EXPECT_FALSE(p.toJson().contains("default_function_policy"));
 }
+
+// The per-project wall-time maximum. Resolved by a pure function for the same
+// reason the function policy is: the precedence is the behaviour, and it should
+// be assertable without a database, a runner or a clock.
+
+TEST(MaxFunctionWallTime, AbsentMeansNoProjectCap) {
+    // 0, not "no time": the runner reads 0 as "the ceiling is the only cap".
+    EXPECT_EQ(maxFunctionWallTimeMsFor(nullptr), 0);
+    const ProjectSettings p;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 0);
+}
+
+TEST(MaxFunctionWallTime, UsesTheProjectValueWhenSet) {
+    ProjectSettings p;
+    p.maxFunctionWallTimeMs = 30000;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 30000);
+}
+
+TEST(MaxFunctionWallTime, ANonPositiveStoredValueIsTreatedAsUnset) {
+    // A fat-fingered 0 means "I did not mean to set one", not "no function in
+    // this project may ever run".
+    ProjectSettings p;
+    p.maxFunctionWallTimeMs = 0;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 0);
+    p.maxFunctionWallTimeMs = -1;
+    EXPECT_EQ(maxFunctionWallTimeMsFor(&p), 0);
+}
+
+TEST(MaxFunctionWallTime, RoundTripsAndIsNotWrittenWhenUnset) {
+    ProjectSettings p;
+    EXPECT_FALSE(p.toJson().contains("max_function_wall_time_ms"));
+
+    p.maxFunctionWallTimeMs = 45000;
+    const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
+    ASSERT_TRUE(back.maxFunctionWallTimeMs.has_value());
+    EXPECT_EQ(*back.maxFunctionWallTimeMs, 45000);
+}
+
+TEST(MaxFunctionWallTime, ABudgetOnlyProjectIsNotTreatedAsEmpty) {
+    // Otherwise clearing an embedding override would delete the settings
+    // document and silently remove the project's cap with it.
+    ProjectSettings p;
+    p.maxFunctionWallTimeMs = 1000;
+    EXPECT_TRUE(p.hasAnyOverrides());
+    EXPECT_FALSE(p.hasEmbeddingOverrides());
+}

+ 1 - 2
tests/test_runner_client.cpp

@@ -2,8 +2,7 @@
 //
 // Every test here runs against a real cpp-httplib server in-process, so the
 // pool's HTTP path is exercised for real without a QuickJS runner and without
-// the database client - which is what lets this target build on the dev host
-// (CLAUDE.md, "The Void dev host can no longer build the C++ natively").
+// the database client, so this target builds anywhere the client does not.
 //
 // The test this file exists for is RunFailureIsNotRetried. Everything else
 // guards it: if a runner answering "your function threw" were treated as a

Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff