Jelajahi Sumber

feat: one release - curl 8.23.0, the client pin at 2.20.0, and the two slugs it unblocks

Everything that was waiting on a version or a pin, in one payload, because
three separate windows for three small changes is worse than one window
for all of them.

curl 8.23.0 (CVE-2026-92387 reaches our imap/smtp surface and bypasses
CURLOPT_TIMEOUT_MS, which is how MailBudget::totalMs is enforced). Taken
from the branch as its own commit rather than merged: that branch predates
0.14.0, so merging it would have deleted the error hook, the fn gate and
the scope refusal. Only its four runner files were applied, after checking
main had not touched any of them.

DB_CLIENT_VERSION 2.17.2 -> 2.20.0, which is what makes this one release
rather than three. It unblocks two things that were each waiting on it:

  _expires_at now comes back on reads and in the export. Measured with a
  control rather than assumed - a row stored with ?ttl_seconds=3600 carries
  it, a row stored without one carries NO such field, and the arithmetic
  checks against the clock. So absence means no expiry and a caller must
  test for the key, not for a zero. llms.txt had said the field "is not yet
  RETURNED", which was true when written and is now false; in an API
  reference that gets REPLACED rather than labelled, because a consumer
  reading it writes code that never looks for the field.

  invalid_pattern -> 422 with its own slug. Ships ahead of the server that
  produces it, which is sound because the dependency is the SERVER reaching
  2.20.x and never the client - this repo had that premise backwards and
  filed it under the pin move.

Both hand-maintained Depends floors moved with the pin. Nothing computes
them, so a pin move that left them at 2.17.2 would let apt install this
binary against a client that cannot resolve the calls it now makes: installs
clean, segfaults on the next restart. The consequence of the floor is that
this deb is NOT deployable until prod's client moves, which is deliberate -
it ties the release to the database window rather than letting it go out and
fail later.

Also: the error slug is logged on every 4xx and 5xx. We built a structured
reason for every refusal and kept none of it, so a refused request left only
a status code - which twice decided a diagnosis, once a three-day 403 and
once a single 422 whose cause was narrowed by five eliminations and then
could not be closed at all. The slug, status and route are logged; details
deliberately are not, since it echoes the caller's own input.

And the event watcher now names what a tolerated failure COSTS. Its catch
said "already logged", which was true of buildPlan then and now - but it was
a premise held in another function with nothing enforcing it, and "could not
read the registry" never said the thing an operator needs: that a function
deployed since the last good refresh is not being watched, while every
existing function carries on working so nothing looks wrong.

runs_kept 50 -> 500, per function. Measured at ~711 bytes a row, so the old
default cost ~640 KB across one project's 18 functions and this costs ~6 MB
against a 607 MB store. The near-refusal of this request reasoned from a
true fact with nothing counted in it and was wrong by about 100x.

1345 tests pass, run serially. The invalid_pattern mapping and the
Retry-After pairings were each deliberately falsified.
fszontagh 1 bulan lalu
induk
melakukan
f85f905f05

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.15.0
+0.16.0

+ 7 - 1
api/llms.txt

@@ -100,7 +100,13 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
   **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: **`field`** when one field collided or **`fields`** when several, **`values`** (an OBJECT of the colliding field/value pairs, not a bare `value`), `conflicting_document_id` (the document already holding it), and `relation` or `current_version` where they apply. A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A failed conditional write is **409** `version_conflict`. A missing collection is **404** only when its absence is CONFIRMED: if the database cannot be reached the answer is **503**, never a 404, so a 404 is always safe to treat as definitive and unretryable. A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write. **On a `kind=vector` collection, a PUT whose body carries no vector is refused **422** `vector_replace_unsafe`.** A replace discards the stored embedding and the caller cannot prevent it, because no read returns the vector - so there is nothing to put back. Use `PATCH` for fields, or `POST .../vectors` to store a document together with its vector.
 
-  **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`, `_expires_at`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields. **`_expires_at` is reserved and stripped, but this server does not yet RETURN it** - it is the document's absolute expiry in epoch ms, the database has always sent it, and the client library we currently ship drops it before we see it, so reads omit it today and will start carrying it when that pin moves. It is stripped from writes already so that no row is ever stored with an invisible copy of it. Set an expiry with `?ttl_seconds=`, never by posting this field. When it does appear, **absent means no expiry, never zero**, and a value may legitimately be in the PAST: expiry is swept lazily, so a row can outlive its deadline - which is also why a restore must LEAVE OUT an expired row rather than put it back permanent.
+  **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`. The metadata fields below (`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by`, `_updated_by`, `_expires_at`) are stripped from every write body, so you can read a document, edit a field and send the whole thing back without storing stale metadata as real fields. **`_expires_at` is reserved and stripped on writes, and is now RETURNED on reads and in the export.** It is the document's absolute expiry in epoch ms. Measured with a control: a row stored with `?ttl_seconds=3600` reads back carrying `_expires_at`, a row stored without one carries NO such field, and the export carries it on the first and not the second - so **absent means no expiry, never zero**, and you must test for the key's presence rather than for a zero value. Set an expiry with `?ttl_seconds=`, never by posting this field; posting it is silently stripped, which is deliberate - the database would otherwise store an invisible shadow copy that every read overwrites and no filter can reach.
+
+  **A value may legitimately be in the PAST, and this is the part that bites a restore.** Expiry is swept lazily, so a row can outlive its deadline: a backup taken while the server was stopped keeps expired rows until a server opens the file again, and one was measured still physically present **121 hours** past its deadline. **So the restore rule has three branches, not two:** `_expires_at` absent means insert with no TTL; `_expires_at` in the PAST means **skip the row entirely**; otherwise set `?ttl_seconds=` to `ceil((_expires_at - now) / 1000)`.
+
+  **Putting an expired row back makes it IMMORTAL, and every reassuring signal you would check stays green while it happens.** A restored row carries no TTL unless you give it one, so a 48-hour idempotency marker restored two days later suppresses forever the work it was meant to guard for two days. The diff is what hides it: every id back in place, every count matching, the verifier green. Report expired rows you left out (`1341 already present, 1 expired left out`) rather than silently, because the row that mattered is the one nothing would otherwise mention. And note the mirror of the same trap one layer up: **an at-most-once marker with a TTL guards a SCHEDULE and is never evidence of what happened** - if a person can re-run the job later, the record has to live somewhere permanent.
+
+  **FILTERING on `_expires_at` (`lt`, `exists`) needs a database SERVER at 2.19.0 or newer**, unlike reading it, which needs only the client we ship. On an older server the field still comes back on reads and a filter naming it simply matches nothing useful. A row with no expiry is ABSENT for those filters rather than zero, so an upper bound cannot sweep up permanent rows.
 - `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".

+ 1 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.15.0",
+    "version": "0.16.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {

+ 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.17.2-1
+ARG DB_CLIENT_VERSION=2.20.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.17.2-1}"
+DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.20.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.17.2), libssl3t64, libsystemd0, libspdlog1.15, tzdata, ca-certificates, libidn2-0
+Depends: libsmartbotic-db-client (>= 2.20.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata, ca-certificates, libidn2-0
 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.17.2), libssl3t64, libsystemd0, libspdlog1.15, tzdata
+Depends: libsmartbotic-db-client (>= 2.20.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata
 Recommends: smartbotic-vectorapi-webui (= {{VERSION}})
 Breaks: smartbotic-vectorapi-runner (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 25 - 3
runner/CMakeLists.txt

@@ -83,13 +83,35 @@ FetchContent_MakeAvailable(quickjs)
 #   3. The reachable protocol set is exactly: imaps, imap, smtps, smtp. An
 #      advisory in any other protocol is not our exposure.
 #
-# curl-8_22_0 was released 2 Sep 2026; the next release is due 14 Oct 2026.
-# curl's git tags are underscored, which is why this does not read 8.22.0.
+# curl-8_23_0 was released 14 Oct 2026 and carries 22 advisories.
+# curl's git tags are underscored, which is why this does not read 8.23.0.
+#
+# WHY THIS BUMP WAS TAKEN, AND WHY IT WAS NOT AN EMERGENCY. The one rated HIGH,
+# CVE-2026-92392, is a use-after-free in HTTP/2 UPLOAD handling, and we cannot
+# reach it for two independent reasons visible in this very file:
+# CURL_DISABLE_HTTP and USE_NGHTTP2 OFF. There is no HTTP in this curl at all,
+# let alone HTTP/2. So the severity column pointed away from the thing that
+# actually matters here, which is the whole reason obligation 2 above is worded
+# the way it is.
+#
+# The one that DOES reach us is rated Low: CVE-2026-92387 names the "ping-pong"
+# protocols - FTP, IMAP, POP3 and SMTP - so it covers exactly the two we keep.
+# A server that keeps feeding data at the client's read speed while permanently
+# omitting the final control-response line sends libcurl into a loop whose exit
+# condition can never be met, BYPASSING CURLOPT_TIMEOUT_MS. That option is how
+# MailBudget::totalMs is enforced (net/mail_session.cpp), and because a blocking
+# host call cannot be interrupted the QuickJS wall budget cannot rescue the run
+# either - so the unbounded call would hold its lease on a runtime the whole
+# pool shares. MailStall.AServerThatNeverCompletesACommandIsStillBounded does
+# NOT prove we were safe before this bump: it is bounded by curl's own timeout,
+# i.e. by the option the flaw defeats, so it reached the healthy path rather
+# than the flawed loop. A bounded pass was equally consistent with "immune" and
+# "not reproduced", which is why the fix was taken rather than argued away.
 #
 # SFTP is deliberately NOT in the surface, which is what keeps this to ONE
 # vendored upstream: SFTP would require libssh2 as well, and libssh2 is far
 # less watched than curl while having had remotely reachable issues.
-set(SVAPI_CURL_TAG "curl-8_22_0" CACHE STRING "curl git tag to vendor")
+set(SVAPI_CURL_TAG "curl-8_23_0" CACHE STRING "curl git tag to vendor")
 option(SVAPI_VENDOR_CURL "Vendor libcurl rather than linking the system one" ON)
 
 if(SVAPI_VENDOR_CURL)

+ 6 - 1
runner/src/net/imap_fetch.hpp

@@ -390,7 +390,12 @@ const ImapFetchRecord* findByUid(const std::vector<ImapFetchRecord>& messages, u
 /// libcurl count the trailing protocol text toward N, so the literal libcurl
 /// delivers is padded with the response's own framing. curl reports success:
 /// measured against 8.22.0, an announce of 50 for a 40-byte body yielded
-/// `CURLE_OK` and a 50-byte literal whose tail was `)<CRLF>A003 OK`.
+/// `CURLE_OK` and a 50-byte literal whose tail was `)<CRLF>A003 OK`. Re-measured
+/// against 8.23.0 when the pin moved, and now pinned by a live test rather
+/// than by this comment: `ImapFixture.AnOverstatedLiteralIsDELIVEREDasSuccess
+/// AndCaughtOnlyByItsCONTENT` drives a real curl against a server that
+/// overstates, so if a later curl ever starts refusing the miscount this
+/// function becomes dead code and the suite says so instead of staying green.
 ///
 /// It cannot be caught structurally. curl consumes the real `)` and the tagged
 /// line in the HEALTHY case too, so a padded response and a correct one are

+ 11 - 1
runner/tests/fake_mail_server.hpp

@@ -156,6 +156,15 @@ class FakeImapServer : public FakeLineServer {
 public:
     /// What a UID FETCH returns as the message body.
     std::string messageBody = "From: a@example.com\r\nSubject: hello\r\n\r\nbody text\r\n";
+    /// Announce `{n}` this many bytes LARGER than the body actually sent, to
+    /// model the server that corrupts silently: libcurl counts the response's
+    /// own framing toward the announced count and reports SUCCESS, so the
+    /// literal it delivers is padded with `)<CRLF>A<digits> OK`. This is the
+    /// only way to exercise `literalEndsWithFraming` against real curl rather
+    /// than against a hand-written buffer, which matters on every pin bump -
+    /// if curl ever started refusing the miscount, the detector would be dead
+    /// code and nothing else would say so.
+    size_t literalOverstateBytes = 0;
     /// Untagged lines emitted on SELECT/EXAMINE. These exist so a test can
     /// observe WHERE they end up: whether curl hands a custom request's caller
     /// the SELECT chatter as well as the command's own response.
@@ -185,7 +194,8 @@ protected:
             // The response to a BODY.PEEK[] fetch comes back labelled BODY[],
             // without the .PEEK. A parser that looks for the string it sent
             // will not find it, which is a real and easily missed trap.
-            std::string out = "* 1 FETCH (UID 7 BODY[] {" + std::to_string(messageBody.size()) +
+            std::string out = "* 1 FETCH (UID 7 BODY[] {" +
+                              std::to_string(messageBody.size() + literalOverstateBytes) +
                               "}\r\n" + messageBody + ")\r\n";
             return out + tag + " OK fetched\r\n";
         }

+ 76 - 0
runner/tests/mail_session_test.cpp

@@ -7,6 +7,7 @@
 #include <thread>
 
 #include "fake_mail_server.hpp"
+#include "net/imap_fetch.hpp"
 #include "net/mail_session.hpp"
 
 using namespace svapi::runner::net;
@@ -129,6 +130,81 @@ TEST_F(ImapFixture, CurlConsumesTheClosingParenAndTheTaggedCompletionLine) {
     mailGlobalCleanup();
 }
 
+TEST_F(ImapFixture, AnOverstatedLiteralIsDELIVEREDasSuccessAndCaughtOnlyByItsCONTENT) {
+    // The premise the whole padded-literal defence rests on, pinned against
+    // REAL curl rather than a hand-written buffer.
+    //
+    // A server announcing `{n}` larger than the body it sends is not refused by
+    // libcurl: curl counts the response's own framing toward n and reports
+    // CURLE_OK, so the literal handed to the write callback is the body plus
+    // `)<CRLF>` plus the first bytes of the tagged completion. There is no
+    // structural signal - curl strips the real framing in the healthy case too,
+    // so this response and a correct one are byte-for-byte the same SHAPE. Only
+    // the CONTENT differs, which is why `literalEndsWithFraming` exists.
+    //
+    // This is a PIN-BUMP test. It was measured once on 8.22.0 and recorded in a
+    // comment, and a comment cannot notice when curl changes: were a later curl
+    // to start rejecting the miscount, the detector would become dead code and
+    // nothing in the suite would say so. If this test ever fails because the
+    // command itself failed, that is the news - read it as "curl now catches
+    // this", not as a broken test.
+    ASSERT_EQ(mailGlobalInit(), std::string());
+    server.messageBody = "0123456789";       // 10 bytes
+    server.literalOverstateBytes = 10;       // ... announced as 20
+    ImapSession session;
+    ASSERT_TRUE(session.open(accountFor(server.port()), optionsFor()).ok());
+
+    std::string response;
+    const MailFailure f = session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", response);
+
+    // Half one: curl did NOT notice. Stated as its own assertion because it is
+    // the surprising half and the reason the content check has to exist.
+    ASSERT_TRUE(f.ok()) << "curl refused the overstated literal itself (" << f.slug << ": "
+                        << f.message << ") - if that is now curl's behaviour, "
+                        << "literalEndsWithFraming has become dead code and this test should say "
+                        << "so rather than be deleted";
+    // Exactly 20 bytes of "literal", the last ten of them protocol text. The
+    // header is asserted whole and the tail by SHAPE, because the tag is
+    // curl's own and its NUMBER depends on how many commands preceded this one
+    // on the session - pinning "A003" would make the test fail if a login or a
+    // SELECT were ever added ahead of it, which is not what it is testing.
+    const std::string header = "* 1 FETCH (UID 7 BODY[] {20}\r\n";
+    ASSERT_EQ(response.rfind(header, 0), 0u) << "unexpected response: " << response;
+    const std::string literal = response.substr(header.size());
+    EXPECT_EQ(literal.size(), 20u) << "curl delivered a different count than it was announced";
+    EXPECT_EQ(literal.rfind("0123456789)\r\nA", 0), 0u)
+        << "the padding was not the response's own framing: " << literal;
+    EXPECT_NE(literal.find(" OK"), std::string::npos) << literal;
+
+    // Half two: the detector fires on what curl ACTUALLY delivered. The two
+    // parses mirror `parseCurlFetch` in host_context.cpp - the direct parse is
+    // short of its own announced count, and the framed re-parse is what reaches
+    // the content check.
+    const ImapFetchResult direct = parseFetchResponse(response);
+    EXPECT_NE(direct.status, ImapParse::Ok) << "the direct parse should still be short";
+    const ImapFetchResult framed = parseFetchResponse(response + ")\r\n");
+    ASSERT_EQ(framed.status, ImapParse::Ok);
+    ASSERT_EQ(framed.messages.size(), 1u);
+    ASSERT_FALSE(framed.messages.front().bodyParts.empty());
+    EXPECT_TRUE(literalEndsWithFraming(framed.messages.front().bodyParts.begin()->second))
+        << "curl's padding was not recognised as framing, so a function would have received "
+           "protocol text welded to the end of a message body";
+
+    // The CONTROL, and it is what makes the assertion above mean anything: the
+    // same server without the overstatement delivers a literal the detector
+    // does NOT flag. Without this, the test would pass just as well against a
+    // detector that flagged everything.
+    server.literalOverstateBytes = 0;
+    std::string honest;
+    ASSERT_TRUE(session.command("INBOX", "UID FETCH 7 BODY.PEEK[]", honest).ok());
+    const ImapFetchResult good = parseFetchResponse(honest + ")\r\n");
+    ASSERT_EQ(good.status, ImapParse::Ok);
+    ASSERT_FALSE(good.messages.front().bodyParts.empty());
+    EXPECT_FALSE(literalEndsWithFraming(good.messages.front().bodyParts.begin()->second))
+        << "a correct response was flagged as padded, which would refuse every good fetch";
+    mailGlobalCleanup();
+}
+
 TEST_F(ImapFixture, TheSessionReusesOneConnectionForSeveralCommands) {
     // One handle per (run, account): a fresh handle per command would mean a
     // TCP connect, a TLS handshake and a LOGIN every time, which is both slow

+ 26 - 3
src/config.hpp

@@ -20,9 +20,32 @@ struct Config {
     /// A static list on purpose - dynamic registration is only worth its
     /// failure modes once autoscaling exists.
     std::vector<std::string> runnerEndpoints;
-    /// Runs kept per function. There is no scheduler to prune them yet, so the
-    /// log is trimmed on write; unbounded, a busy function fills the database.
-    uint32_t functionRunsKept = 50;
+    /// Runs kept PER FUNCTION (trimOldest filters on function_id). There is no
+    /// scheduler to prune them yet, so the log is trimmed on write; unbounded,
+    /// a busy function fills the database. 0 keeps everything.
+    ///
+    /// Raised from 50 after a consumer asked for more history and the refusal
+    /// was nearly given on a true general fact with no measurement in it -
+    /// "store size is what took prod down this morning, so today is the wrong
+    /// day to grow a collection". Measured instead: a run row is **~711 bytes**
+    /// (601 rows / 427,481 bytes on one project's run log), so the OLD default
+    /// cost about 640 KB across that project's 18 functions and this one costs
+    /// roughly 6 MB - against a 607 MB store. The near-refusal was wrong by
+    /// about 100x, in the direction of denying a consumer something cheap they
+    /// had a real need for.
+    ///
+    /// 500 rather than "as much as possible": the number has to stay small
+    /// enough that a minute-cron cannot outrun it in a way nobody priced, and
+    /// at one run a minute 500 is about eight hours of history - which is the
+    /// shape of question the log actually gets asked ("what happened
+    /// overnight"), not a week of it.
+    ///
+    /// Note a consumer's report that `GET .../logs` caps at 50 however high
+    /// `limit` is set is NOT the accepted-and-ignored family: `limit` is
+    /// honoured and clamped to the retained count, because rows beyond it were
+    /// trimmed on write and do not exist to return. Raising THIS is the remedy;
+    /// there was never anything to fix in the handler.
+    uint32_t functionRunsKept = 500;
     /// Shared secret presented to the runners. Prefer SVAPI_RUNNER_TOKEN in
     /// vectorapi.env over config.json, which is a conffile and tends to be
     /// world-readable. Empty is valid only for a loopback runner.

+ 28 - 0
src/db_errors.cpp

@@ -90,6 +90,34 @@ ApiError translate(Code code, const std::string& message, const std::string& not
                 // and silently matched nothing. So this refusal turns a silently
                 // empty result into a visible error.
                 return ApiError(ErrCode::Unprocessable, "encrypted_field", message, details);
+            if (reason == "invalid_pattern")
+                // database 2.20.0 moved regex evaluation to RE2, which refuses
+                // lookaround and backreferences outright rather than
+                // interpreting them. So a `field:regex:(?<=x)y` filter, a
+                // schema `pattern`, or a vector-search filter carrying one is
+                // now refused instead of evaluated.
+                //
+                // Its own slug rather than `validation`, for the same reason
+                // `encrypted_field` has one: the request is well formed and the
+                // field is spelled correctly, and no correction of the BODY
+                // helps. The remedy is to rewrite the PATTERN in a syntax RE2
+                // supports - which for the common case of a word boundary
+                // around non-ASCII text means a character class rather than a
+                // lookbehind, since that is what a caller reaches for when
+                // JavaScript's ASCII-only `\b` fails them.
+                //
+                // What it REPLACES is the usual shape in this file: before
+                // 2.20.0 such a pattern was accepted by std::regex and quietly
+                // matched something else, or threw and was reported as our
+                // fault. A visible refusal naming the pattern beats either.
+                //
+                // Dormant until the SERVER reaches 2.20.x - the client side of
+                // this needs nothing, which this file had recorded backwards
+                // for a while. On an older server the reason never arrives and
+                // the fall-through `validation` answer is correct, because
+                // std::regex really did refuse the request rather than the
+                // pattern being unsupported in principle.
+                return ApiError(ErrCode::Unprocessable, "invalid_pattern", message, details);
             if (reason == "schema_violation")
                 // A write refused by the collection's schema (database 2.16.0).
                 // Its own slug because the remedy is specific and the payload

+ 26 - 3
src/function_events.cpp

@@ -80,11 +80,34 @@ bool FunctionEventWatcher::refresh() {
     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.
+        // 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. That decision is still right.
+        //
+        // What it used to say was "Already logged", and that was TRUE of
+        // buildPlan both then and now - it warns and rethrows on each of its
+        // two throwing paths. But it was a premise held in another function
+        // with nothing enforcing it: a third throwing path added there without
+        // a log would turn this into a silent swallow while this comment went
+        // on claiming otherwise.
+        //
+        // So it logs the CONSEQUENCE rather than repeating the cause, which is
+        // also the part buildPlan cannot know and the part an operator needs.
+        // "could not read the registry" does not say that a function deployed
+        // since the last good refresh is NOT BEING WATCHED - and because the
+        // old plan keeps working, every event for every existing function
+        // still arrives, so nothing else looks wrong. A tolerated failure has
+        // to name what it is costing, or it reads as a hiccup.
+        ++staleRefreshes_;
+        spdlog::warn("function event watcher kept its previous watch plan ({} consecutive "
+                     "failed refreshes); functions added or changed since the last successful "
+                     "refresh are NOT receiving database events",
+                     staleRefreshes_);
         return false;
     }
+    // Reaching here means the plan is current again; the counter exists to make
+    // a PERSISTENT failure legible, not to count lifetime hiccups.
+    staleRefreshes_ = 0;
 
     auto snapshot = std::make_shared<const FunctionWatchPlan>(std::move(fresh));
 

+ 7 - 0
src/function_events.hpp

@@ -371,6 +371,13 @@ private:
     std::deque<PendingJob>       pending_;
     uint64_t                     dropped_ = 0;
 
+    /// Consecutive failed refreshes, so a PERSISTENT failure to re-read the
+    /// registry is legible rather than looking like a hiccup. Unguarded on
+    /// purpose and safe: refresh() runs on exactly one thread at a time -
+    /// start() calls it once before the watcher thread is created, and every
+    /// later call is from loop() on that thread.
+    uint64_t                     staleRefreshes_ = 0;
+
     mutable std::mutex           lifeM_;
     bool                         stop_ = false;
     bool                         started_ = false;

+ 45 - 3
src/server.cpp

@@ -5,6 +5,8 @@
 #include "errors.hpp"
 #include "json_http.hpp"
 #include "rate_limiter.hpp"
+#include <spdlog/spdlog.h>
+
 #include <chrono>
 #include <fstream>
 #include <sstream>
@@ -113,10 +115,41 @@ void requireCapability(ServerDeps& d, const ApiKey& k, const httplib::Request& r
 }
 
 void ApiServer::registerRoutes() {
-    svr_.set_exception_handler([](const httplib::Request&, httplib::Response& res, std::exception_ptr ep) {
+    svr_.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception_ptr ep) {
+        // RECORD THE SLUG. We build a structured reason for every refusal and
+        // used to keep NONE of it for a 4xx, so a refused request left only its
+        // status code behind - and a status code is shared by a dozen causes.
+        // Twice that has decided a diagnosis: a three-day 403 where only the
+        // access log knew anything, and one failed insert whose cause was
+        // narrowed by five eliminations and then could not be closed at all,
+        // because the one 422 in the window was already gone.
+        //
+        // What is logged is the SLUG, the status and the route. Deliberately
+        // NOT `details`: it legitimately echoes the caller's own input - the
+        // colliding values of a duplicate, the violating paths of a schema
+        // refusal - and a diagnostic log is the wrong place for tenant data we
+        // were only ever meant to hand straight back. The slug is ours and
+        // names the decision we took, which is the part nobody can reconstruct
+        // afterwards.
+        //
+        // A 4xx is at INFO rather than warn: it is the caller's business and
+        // routine (prod sees a few hundred 409s in a quiet afternoon from one
+        // consumer's idempotent writes), so warning on it would train people to
+        // filter the level that also carries real faults. But it must stay
+        // ABOVE debug - a record only kept when someone thought to raise the
+        // level is no record at all, since nobody raises it before the failure
+        // they could not explain. A 5xx is ours and warns.
+        auto record = [&req](const ApiError& e) {
+            const int status = httpStatus(e.code);
+            if (status >= 500)
+                spdlog::warn("request failed: {} {} -> {} {}", req.method, req.path, status, e.slug);
+            else
+                spdlog::info("request refused: {} {} -> {} {}", req.method, req.path, status, e.slug);
+        };
         // One sender for every classified failure, so a database-raised 429
         // carries Retry-After exactly as one of ours does.
-        auto send = [&res](const ApiError& e) {
+        auto send = [&res, &record](const ApiError& e) {
+            record(e);
             // One decider (errors.hpp), so the header cannot drift from the
             // raise sites that set it - and so the handler never has to
             // recover the CAUSE by matching on a slug, which would be the
@@ -139,7 +172,16 @@ void ApiServer::registerRoutes() {
         // std::runtime_error, so a more general arm placed first would swallow
         // every one of these and the mapping would silently never run.
         catch (const smartbotic::database::Client::Error& e) { send(apiErrorFor(e)); }
-        catch (const std::exception& e) { sendJson(res, 500, errorBody("internal", e.what())); }
+        catch (const std::exception& e) {
+            // The one arm with no classification at all. It logs the exception
+            // TEXT as well as the slug, because unlike every arm above there is
+            // no slug that distinguishes one of these from another - this is
+            // the branch where a 500 means "we do not know", and it is ours
+            // rather than the caller's, so there is no tenant data concern.
+            spdlog::error("request failed: {} {} -> 500 internal: {}", req.method, req.path,
+                          e.what());
+            sendJson(res, 500, errorBody("internal", e.what()));
+        }
     });
 
     // SPA history fallback: a hard navigation / refresh / direct URL to a client-side

+ 27 - 0
tests/test_db_errors.cpp

@@ -352,3 +352,30 @@ TEST(DbErrors, AnUnrecognisedInvalidArgumentReasonStaysGenericValidation) {
     const svapi::ApiError e = svapi::apiErrorFor(d, "no such document");
     EXPECT_EQ(e.slug, "validation");
 }
+
+TEST(DbErrors, AnRE2RefusedPatternIsItsOwnSlugRatherThanGenericValidation) {
+    // database 2.20.0 evaluates REGEX filters with RE2, which REFUSES lookaround
+    // and backreferences rather than interpreting them. Its own slug for the
+    // same reason `encrypted_field` has one: the request is well formed and the
+    // field is spelled correctly, and no correction of the BODY helps - the
+    // remedy is to rewrite the PATTERN.
+    //
+    // Dormant until the SERVER reaches 2.20.x. This file had the premise
+    // backwards for a while, filing it under the client pin; the client side
+    // needs nothing, so the mapping can ship ahead of the server that produces
+    // the reason.
+    smartbotic::database::Client::FailureDetail d;
+    d.code = smartbotic::database::Client::ErrorCode::InvalidArgument;
+    d.reason = "invalid_pattern";
+    d.message = "regex not supported by RE2: lookbehind at offset 0";
+    d.fields = {"name"};
+    const svapi::ApiError e = svapi::apiErrorFor(d, "no such document");
+    EXPECT_EQ(e.slug, "invalid_pattern");
+    EXPECT_EQ(svapi::httpStatus(e.code), 422);
+    // Permanent, so it must advise no wait. A caller that retried a pattern RE2
+    // will never accept would retry forever.
+    EXPECT_EQ(svapi::retryAfterSeconds(e), 0);
+    // The server sends `fields` = the filter, so the caller learns WHICH one.
+    ASSERT_TRUE(e.details.contains("field")) << e.details.dump();
+    EXPECT_EQ(e.details.at("field"), "name");
+}