Browse Source

fix: stop reporting an unreachable database as missing data

Reviewing the 2.12.1-2.12.3 releases I had skipped. Nothing newer than
2.12.4 exists - the remote's top tag and main head match ours and the daemon
container is already on it - but bumping the pin 2.12.0 -> 2.12.4 in one step
meant only 2.12.4 was read, and two intermediate releases change refusal
shapes we consume. Neither is visible to an ABI check: client/ is untouched in
both and the library exports the same 7174 symbols. What changed is the status
and detail a refusal arrives with.

2.12.1 made a duplicate primary id a typed refusal (AlreadyExists, reason
"duplicate_id", conflicting_id set) where it had been a bare runtime_error
arriving as Internal. 2.12.3 made the file size limit refuse mid-stream as
InvalidArgument with reason file_too_large or mime_type_not_allowed, instead
of buffering the whole body and answering Internal.

The review found a crash that predates all of it. uploadFile, getFileInfo and
listFiles throw on a failed status and always have; only downloadFile was
guarded. retention_service runs its own std::thread and contains no try or
catch anywhere, while calling listFilesForWorkflow and setFileTtl - so a
database blip during a retention sweep was std::terminate, taking the
webserver down rather than losing one sweep. The audit missed it because the
2.12.4 notice is what prompted the audit and the file API was not in it.

The client also calls handler(out) from its stream reader thread with no catch
of its own. Our watcher callback handles arbitrary JSON from whoever wrote the
document, so one malformed event ended the process. Guarded here, and upstream
is adding a catch in 2.13.0.

setFileTtl cannot be fixed from this side: it returns plain false for every
failed status and has no Failure& overload, so no reason can reach us. It no
longer claims the file is absent - which during an outage asserted something
it could not know - and says so in the message instead. Upstream has taken it,
with deleteFile, for 2.13.0.

Then the same flattening turned up above the adapter, which is where it did
the visible damage: 24 sites across 6 controllers answered a definite 404 for
any storage failure, so during a blip the editor rendered "not found" over
generated images sitting safely in the file store, and 404 tells a client not
to retry. They now share one decision in api/storage_error.hpp: transient
becomes 503 and says the data is still there, a genuine absence answers
exactly as before, and anything else is a 500 rather than a claim about
existence. The deliberate 404-not-403 permission responses are untouched -
they are not storage failures and do not go through it.

The duplicate check in the integration script was weaker than it looked: it
searched the message for words like "exist", and 2.12.0 already said "already
exists" in its bare Internal error, so it passed on the version it existed to
distinguish. It now asserts the reason and the conflicting id by name, neither
of which 2.12.0 carried. Renamed verify-db-2120.py -> verify-db-212x.py since
it now covers the whole line.

The C++ failure test gained the five file calls. setFileTtl gets its own
weaker expectation with the reason stated, rather than being dropped or
allowed to loosen the shared check - it must still report failure and must not
claim absence. 15/15.

Verified live, both directions: a bogus id still answers 404 while the
database is up, and with the container stopped an existing execution and a
file both answer 503 with a retryable message while the webserver stays up and
/health keeps answering 200.

2.12.2 needs nothing from us: indexes are declared only on fixed system
collections and re-declared every boot, and retention drops only per-workflow
collections that are never recreated under the same name.

Tests: node 103 passed / 0 failed / 2 skipped (the known #106 sd.cpp race),
4 C++ binaries, verify-db-212x.py 4/4.

Rollback: smartbotic-automation:pre-2.12.4.
fszontagh 1 tháng trước cách đây
mục cha
commit
9279ca1f4c

+ 2 - 2
CLAUDE.md

@@ -50,14 +50,14 @@ are leftovers from the step after that.
 ```bash
 ./scripts/run-node-tests.sh      # every node, through a running webserver + runner
 ./scripts/run-cpp-tests.sh       # pure C++ logic, compiled in the build image
-python3 scripts/verify-db-2120.py  # database 2.12.0 behaviour, needs the live stack
+python3 scripts/verify-db-212x.py  # database 2.12.x behaviour, needs the live stack
 ```
 
 `run-cpp-tests.sh` compiles each `tests/cpp/*_test.cpp` in the build image, so a
 test needing a toolchain brings its own; a test names extra sources on a
 `// sources:` line and extra link flags on a `// libs:` line.
 `storage_read_failures_test.cpp` is written against the client 2.12.4 read
-contract and is expected to FAIL on 2.12.0 - see packaging/Dockerfile.base. `verify-db-2120.py` covers what a unit test cannot show -
+contract and is expected to FAIL on 2.12.0 - see packaging/Dockerfile.base. `verify-db-212x.py` covers what a unit test cannot show -
 concurrent increments, a watcher ignoring its own writes while still seeing
 other people's, and a refusal arriving classified.
 

+ 66 - 18
lib/storage/storage_client.cpp

@@ -132,6 +132,8 @@ std::string describeDbFailure(const char* what,
 }
 
 // From client 2.12.4 a failed READ throws instead of answering "nothing there".
+// The file calls (upload, download, getFileInfo, listFiles, setFileTtl) have
+// thrown since well before that, which is why this is not named for reads.
 // Before, a blip was indistinguishable from a genuine absence: get() returned
 // nullopt, the list reads returned empty and getCollectionConfig() returned the
 // DEFAULTS. Upstream changed it because a consumer turned one such blip into a
@@ -146,7 +148,7 @@ std::string describeDbFailure(const char* what,
 //
 // A genuine absence still comes back as nullopt/empty and does not throw, so
 // "not found" keeps its own code and only a real failure gets the transient one.
-Error dbReadError(const char* what,
+Error dbCallError(const char* what,
                   const std::string& collection,
                   const std::string& id,
                   const database::Client::Error& e) {
@@ -160,7 +162,7 @@ Result<nlohmann::json> StorageClient::get(const std::string& collection, const s
     try {
         opt = impl_->client_->get(collection, id);
     } catch (const Client::Error& e) {
-        return dbReadError("Get", collection, id, e);
+        return dbCallError("Get", collection, id, e);
     } catch (const std::exception& e) {
         return Error(ErrorCode::DatabaseError,
                      "Get failed: " + collection + "/" + id + ": " + e.what());
@@ -339,7 +341,7 @@ Result<QueryResult> StorageClient::query(const std::string& collection, const Qu
             return Error(ErrorCode::CollectionNotFound,
                          "Query failed for '" + collection + "': " + e.what());
         }
-        return dbReadError("Query", collection, "", e);
+        return dbCallError("Query", collection, "", e);
     } catch (const std::exception& e) {
         return Error(ErrorCode::CollectionNotFound,
                      "Query failed for '" + collection + "': " + e.what());
@@ -485,7 +487,7 @@ Result<CollectionInfo> StorageClient::getCollectionInfo(const std::string& name)
     try {
         upstream = impl_->client_->getCollectionInfo(name);
     } catch (const Client::Error& e) {
-        return dbReadError("getCollectionInfo", name, "", e);
+        return dbCallError("getCollectionInfo", name, "", e);
     }
     if (!upstream.has_value()) {
         return Error(ErrorCode::CollectionNotFound, "No such collection: " + name);
@@ -527,7 +529,7 @@ Result<CollectionConfig> StorageClient::getCollectionConfig(const std::string& c
     try {
         upstream = impl_->client_->getCollectionConfig(collection);
     } catch (const Client::Error& e) {
-        return dbReadError("getCollectionConfig", collection, "", e);
+        return dbCallError("getCollectionConfig", collection, "", e);
     }
     CollectionConfig cfg;
     cfg.timestamp_precision = upstream.timestampPrecision;
@@ -558,7 +560,7 @@ Result<std::vector<StorageClient::IndexInfo>> StorageClient::listIndexes(const s
     try {
         defs = impl_->client_->listIndexes(collection);
     } catch (const Client::Error& e) {
-        return dbReadError("listIndexes", collection, "", e);
+        return dbCallError("listIndexes", collection, "", e);
     }
     std::vector<IndexInfo> out;
     for (const auto& def : defs) {
@@ -588,7 +590,7 @@ Result<std::vector<std::string>> StorageClient::listCollections() {
     try {
         upstream_names = impl_->client_->listCollections();
     } catch (const Client::Error& e) {
-        return dbReadError("listCollections", "", "", e);
+        return dbCallError("listCollections", "", "", e);
     }
 
     std::vector<std::string> out;
@@ -640,7 +642,7 @@ Result<nlohmann::json> StorageClient::getVersion(const std::string& collection,
     try {
         entry = impl_->client_->getDocumentVersion(collection, id, static_cast<uint64_t>(version));
     } catch (const Client::Error& e) {
-        return dbReadError("getVersion", collection, id, e);
+        return dbCallError("getVersion", collection, id, e);
     }
     if (!entry) return Error(ErrorCode::DocumentNotFound, "Version not found");
     return entry->data;
@@ -656,7 +658,7 @@ Result<VersionListResult> StorageClient::listVersions(const std::string& collect
                                               static_cast<uint32_t>(limit),
                                               static_cast<uint32_t>(offset));
     } catch (const Client::Error& e) {
-        return dbReadError("listVersions", collection, id, e);
+        return dbCallError("listVersions", collection, id, e);
     }
     VersionListResult out;
     out.total_count = static_cast<int64_t>(h.totalCount);
@@ -700,7 +702,7 @@ Result<std::vector<ViewInfo>> StorageClient::listViews() {
     try {
         defs = impl_->client_->listViews();
     } catch (const Client::Error& e) {
-        return dbReadError("listViews", "", "", e);
+        return dbCallError("listViews", "", "", e);
     }
     std::vector<ViewInfo> out;
     for (const auto& v : defs) {
@@ -733,8 +735,25 @@ Result<FileUploadInfo> StorageClient::uploadFile(const std::vector<uint8_t>& dat
     // member, deliberately: adding a member would change that struct's size
     // and an already-installed binary would bind to the new library with the
     // old layout. Keep calling the two-argument form when there is no TTL.
-    auto result = ttl_ms > 0 ? impl_->client_->uploadFile(data, upstream, msToSec(ttl_ms))
-                             : impl_->client_->uploadFile(data, upstream);
+    // uploadFile throws on a failed status - it always has - and 2.12.3 made
+    // that both more likely and more useful: the size limit now refuses
+    // mid-stream rather than after buffering the whole body, and the refusal
+    // arrives as InvalidArgument carrying reason "file_too_large" or
+    // "mime_type_not_allowed" instead of a bare Internal. Unguarded, that
+    // exception left this adapter: from the runner it crossed QuickJS, and
+    // "the file is too big" was never going to reach the person who uploaded it.
+    dbc::Client::FileUploadResult result;
+    try {
+        result = ttl_ms > 0 ? impl_->client_->uploadFile(data, upstream, msToSec(ttl_ms))
+                            : impl_->client_->uploadFile(data, upstream);
+    } catch (const Client::Error& e) {
+        // describeDbFailure appends the reason, so the message says
+        // "[file_too_large]" rather than only that an upload failed.
+        return dbCallError("File upload", "files", meta.name, e);
+    } catch (const std::exception& e) {
+        return Error(ErrorCode::DatabaseError,
+                     "File upload failed: " + meta.name + ": " + e.what());
+    }
     if (result.id.empty()) {
         return Error(ErrorCode::DatabaseError, "File upload failed: " + meta.name);
     }
@@ -763,7 +782,7 @@ Result<std::vector<uint8_t>> StorageClient::downloadFile(const std::string& id)
             return Error(ErrorCode::DocumentNotFound,
                          "File not found: " + id + " (" + e.what() + ")");
         }
-        return dbReadError("downloadFile", "files", id, e);
+        return dbCallError("downloadFile", "files", id, e);
     } catch (const std::exception& e) {
         return Error(ErrorCode::DocumentNotFound,
                      "File not found: " + id + " (" + e.what() + ")");
@@ -775,7 +794,12 @@ Result<std::vector<uint8_t>> StorageClient::downloadFile(const std::string& id)
 }
 
 Result<FileInfo> StorageClient::getFileInfo(const std::string& id) {
-    auto record = impl_->client_->getFileInfo(id);
+    std::optional<database::Client::FileRecord> record;
+    try {
+        record = impl_->client_->getFileInfo(id);
+    } catch (const Client::Error& e) {
+        return dbCallError("getFileInfo", "files", id, e);
+    }
     if (!record) {
         return Error(ErrorCode::DocumentNotFound, "File not found: " + id);
     }
@@ -798,7 +822,12 @@ Result<FileInfo> StorageClient::getFileInfo(const std::string& id) {
 Result<std::vector<FileInfo>> StorageClient::listFilesForWorkflow(const std::string& workflow_id,
                                                                   uint32_t limit, uint32_t offset) {
     if (workflow_id.empty()) return std::vector<FileInfo>{};
-    auto listed = impl_->client_->listFiles("", workflow_id, limit, offset);
+    dbc::Client::FileListResult listed;
+    try {
+        listed = impl_->client_->listFiles("", workflow_id, limit, offset);
+    } catch (const Client::Error& e) {
+        return dbCallError("listFiles", "files", workflow_id, e);
+    }
     std::vector<FileInfo> out;
     out.reserve(listed.files.size());
     for (const auto& f : listed.files) {
@@ -817,9 +846,28 @@ Result<std::vector<FileInfo>> StorageClient::listFilesForWorkflow(const std::str
 }
 
 Result<void> StorageClient::setFileTtl(const std::string& id, int64_t ttl_ms) {
-    if (!impl_->client_->setFileTtl(id, msToSec(ttl_ms))) {
-        return Error(ErrorCode::DocumentNotFound,
-                     "No such file in this project, or it has already expired: " + id);
+    // The one call in the file API that still cannot tell an outage from an
+    // absence. Upstream's setFileTtl returns plain false on ANY failed status
+    // and never throws, and unlike the other writes it has no Failure&
+    // overload, so there is no channel to report a reason through - the 2.12.4
+    // sweep could not reach it. The catch below is therefore belt-and-braces
+    // rather than live today.
+    //
+    // So this does not claim the file is gone. It used to answer
+    // DocumentNotFound, which during a blip asserted something it had no way
+    // of knowing; the retention worker only counts successes, and a file that
+    // keeps its existing expiry is the harmless direction either way.
+    bool ok = false;
+    try {
+        ok = impl_->client_->setFileTtl(id, msToSec(ttl_ms));
+    } catch (const Client::Error& e) {
+        return dbCallError("setFileTtl", "files", id, e);
+    }
+    if (!ok) {
+        return Error(ErrorCode::DatabaseError,
+                     "Could not set the expiry of " + id +
+                         " - no such file in this project, it has already expired, or the "
+                         "database could not be reached; upstream does not distinguish these");
     }
     return {};
 }

+ 15 - 8
scripts/verify-db-2120.py → scripts/verify-db-212x.py

@@ -8,11 +8,13 @@ Three things no unit test can show, because each needs a running stack:
   2. A database-change trigger does not retrigger on the workflow's own writes,
      while still firing on somebody else's.
   3. A duplicate insert is reported as AlreadyExists rather than a generic
-     database error.
+     database error, and from 2.12.1 a duplicate primary ID says so by name:
+     reason "duplicate_id" and the id already holding it. Before 2.12.1 that
+     case threw a bare runtime_error and reached clients as Internal.
 
 Run against a live webserver + runner:
 
-    python3 scripts/verify-db-2120.py
+    python3 scripts/verify-db-212x.py
 """
 import json
 import os
@@ -203,12 +205,17 @@ def main():
             time.sleep(2)
         node = next((n for n in detail.get("nodeExecutions", []) if n.get("nodeId") == "c"), {})
         message = ((node.get("output") or {}).get("result") or {}).get("error", "") or node.get("error", "")
-        # The point is that the message now says what the objection WAS, rather
-        # than only that a write failed.
-        classified = any(word in message.lower()
-                         for word in ("exist", "duplicate", "conflict", "unique"))
-        check("a duplicate insert says it is a duplicate",
-              classified, f"message was: {message[:160]!r}")
+        # Looking for words like "exist" was too weak: 2.12.0 already said
+        # "already exists" in a bare Internal error, so that check passed on the
+        # version it was meant to distinguish. 2.12.1 made a duplicate primary
+        # id a typed refusal, so the message can now be held to naming the
+        # reason AND the id already holding it - neither of which 2.12.0 carried.
+        low = message.lower()
+        names_reason = "duplicate_id" in low
+        names_id = "fixed-id-for-the-duplicate-check" in low
+        check("a duplicate insert names the reason and the conflicting id",
+              names_reason and names_id,
+              f"reason={names_reason} id={names_reason and names_id}, message was: {message[:200]!r}")
     finally:
         call("DELETE", f"/workflows/{dup_wf_id}", token)
 

+ 11 - 5
src/webserver/api/credential_controller.cpp

@@ -3,6 +3,7 @@
 #include <unordered_set>
 #include "credential_controller.hpp"
 #include "logging/logger.hpp"
+#include "storage_error.hpp"
 
 namespace smartbotic::webserver::api {
 
@@ -72,7 +73,8 @@ void CredentialController::shareCredential(const httplib::Request& req, httplib:
     const std::string id = req.matches[1].str();
     auto existing = credential_store_.get(id);
     if (existing.failed()) {
-        sendError(res, "Credential not found", 404);
+        const auto resp = storageErrorResponse(existing.error(), "Credential not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     // 404 rather than 403 for somebody who cannot see it at all: whether a
@@ -124,7 +126,8 @@ void CredentialController::unshareCredential(const httplib::Request& req, httpli
 
     auto existing = credential_store_.get(id);
     if (existing.failed()) {
-        sendError(res, "Credential not found", 404);
+        const auto resp = storageErrorResponse(existing.error(), "Credential not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     if (!mayUse(ctx, existing.value())) {
@@ -345,7 +348,8 @@ void CredentialController::updateCredential(const httplib::Request& req, httplib
     {
         auto existing = credential_store_.get(id);
         if (existing.failed()) {
-            sendError(res, "Credential not found", 404);
+            const auto resp = storageErrorResponse(existing.error(), "Credential not found");
+            sendError(res, resp.message, resp.status);
             return;
         }
         // Somebody it was shared with can see it, so "not found" would be a lie
@@ -396,7 +400,8 @@ void CredentialController::deleteCredential(const httplib::Request& req, httplib
     {
         auto existing = credential_store_.get(id);
         if (existing.failed()) {
-            sendError(res, "Credential not found", 404);
+            const auto resp = storageErrorResponse(existing.error(), "Credential not found");
+            sendError(res, resp.message, resp.status);
             return;
         }
         // Somebody it was shared with can see it, so "not found" would be a lie
@@ -473,7 +478,8 @@ void CredentialController::transferCredentialOwner(const httplib::Request& req,
 
     auto existing = credential_store_.get(id);
     if (existing.failed()) {
-        sendError(res, "Credential not found", 404);
+        const auto resp = storageErrorResponse(existing.error(), "Credential not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     // 404 rather than 403 for somebody who cannot see it at all: whether a

+ 7 - 3
src/webserver/api/execution_controller.cpp

@@ -1,6 +1,7 @@
 #include "execution_controller.hpp"
 #include "../webserver_service.hpp"
 #include "logging/logger.hpp"
+#include "storage_error.hpp"
 #include "common/time_utils.hpp"
 #include "proto/runner.grpc.pb.h"
 #include <grpcpp/grpcpp.h>
@@ -355,7 +356,8 @@ void ExecutionController::getExecution(const httplib::Request& req, httplib::Res
 
     auto result = storage_.get("executions", id);
     if (result.failed()) {
-        sendError(res, "Execution not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Execution not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 
@@ -373,7 +375,8 @@ void ExecutionController::cancelExecution(const httplib::Request& req, httplib::
 
     auto existing = storage_.get("executions", id);
     if (existing.failed()) {
-        sendError(res, "Execution not found", 404);
+        const auto resp = storageErrorResponse(existing.error(), "Execution not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 
@@ -474,7 +477,8 @@ void ExecutionController::retryExecution(const httplib::Request& req, httplib::R
     // Get original execution
     auto exec_result = storage_.get("executions", id);
     if (exec_result.failed()) {
-        sendError(res, "Execution not found", 404);
+        const auto resp = storageErrorResponse(exec_result.error(), "Execution not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 

+ 30 - 0
src/webserver/api/file_controller.cpp

@@ -3,6 +3,24 @@
 
 namespace smartbotic::webserver::api {
 
+namespace {
+
+// "File not found" was the answer to every failure, including a database that
+// could not be reached. That is the worst possible wording for a blip: the
+// files served here are generated images and attachments, so the editor
+// rendered "file not found" over work that was sitting safely in the store,
+// and the obvious conclusion was that it had been lost.
+//
+// A transient failure is reported as one, and 503 also tells the browser and
+// any client that retrying is worth it - which 404 explicitly does not.
+bool isTransient(common::ErrorCode code) {
+    return code == common::ErrorCode::Unavailable ||
+           code == common::ErrorCode::Timeout ||
+           code == common::ErrorCode::ResourceExhausted;
+}
+
+} // namespace
+
 FileController::FileController(storage::StorageClient& storage,
                                auth::AuthMiddleware& middleware)
     : storage_(storage), middleware_(middleware) {}
@@ -38,6 +56,12 @@ void FileController::getFile(const httplib::Request& req, httplib::Response& res
 
     auto content = storage_.downloadFile(id);
     if (content.failed()) {
+        if (isTransient(content.error().code())) {
+            LOG_WARN("File {} could not be read: {}", id, content.error().message());
+            sendError(res, "The file store could not be reached - the file is still there, "
+                           "please retry", 503);
+            return;
+        }
         sendError(res, "File not found", 404);
         return;
     }
@@ -56,6 +80,12 @@ void FileController::getFileInfo(const httplib::Request& req, httplib::Response&
 
     auto info = storage_.getFileInfo(id);
     if (info.failed()) {
+        if (isTransient(info.error().code())) {
+            LOG_WARN("File info for {} could not be read: {}", id, info.error().message());
+            sendError(res, "The file store could not be reached - the file is still there, "
+                           "please retry", 503);
+            return;
+        }
         sendError(res, "File not found", 404);
         return;
     }

+ 5 - 2
src/webserver/api/node_controller.cpp

@@ -4,6 +4,7 @@
 #include <grpcpp/grpcpp.h>
 #include "../grpc/node_sync_service.hpp"
 #include "logging/logger.hpp"
+#include "storage_error.hpp"
 
 namespace smartbotic::webserver::api {
 
@@ -251,7 +252,8 @@ void NodeController::getNode(const httplib::Request& req, httplib::Response& res
 
     auto result = node_store_.get(node_id);
     if (result.failed()) {
-        sendError(res, "Node not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Node not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 
@@ -317,7 +319,8 @@ void NodeController::getNodeCode(const httplib::Request& req, httplib::Response&
 
     auto result = node_store_.get(node_id);
     if (result.failed()) {
-        sendError(res, "Node not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Node not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 

+ 13 - 6
src/webserver/api/project_controller.cpp

@@ -4,6 +4,7 @@
 #include "common/time_utils.hpp"
 #include "common/uuid.hpp"
 #include "logging/logger.hpp"
+#include "storage_error.hpp"
 
 namespace smartbotic::webserver::api {
 
@@ -150,7 +151,8 @@ void ProjectController::getProject(const httplib::Request& req, httplib::Respons
 
     auto project = storage_.get(PROJECTS, id);
     if (project.failed()) {
-        sendError(res, "Project not found", 404);
+        const auto resp = storageErrorResponse(project.error(), "Project not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     if (!access_.allowed(ctx, id, Action::Read)) {
@@ -209,7 +211,8 @@ void ProjectController::updateProject(const httplib::Request& req, httplib::Resp
 
     auto existing = storage_.get(PROJECTS, id);
     if (existing.failed()) {
-        sendError(res, "Project not found", 404);
+        const auto resp = storageErrorResponse(existing.error(), "Project not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     if (!access_.allowed(ctx, id, Action::Manage)) {
@@ -306,7 +309,8 @@ void ProjectController::deleteProject(const httplib::Request& req, httplib::Resp
 
     auto project = storage_.get(PROJECTS, id);
     if (project.failed()) {
-        sendError(res, "Project not found", 404);
+        const auto resp = storageErrorResponse(project.error(), "Project not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     if (project.value().value("type", "") == "personal") {
@@ -359,7 +363,8 @@ void ProjectController::addMember(const httplib::Request& req, httplib::Response
 
     auto project = storage_.get(PROJECTS, id);
     if (project.failed()) {
-        sendError(res, "Project not found", 404);
+        const auto resp = storageErrorResponse(project.error(), "Project not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     if (project.value().value("type", "") == "personal") {
@@ -422,7 +427,8 @@ void ProjectController::updateMember(const httplib::Request& req, httplib::Respo
 
     auto project = storage_.get(PROJECTS, id);
     if (project.failed()) {
-        sendError(res, "Project not found", 404);
+        const auto resp = storageErrorResponse(project.error(), "Project not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     if (!access_.allowed(ctx, id, Action::Manage)) {
@@ -484,7 +490,8 @@ void ProjectController::removeMember(const httplib::Request& req, httplib::Respo
 
     auto project = storage_.get(PROJECTS, id);
     if (project.failed()) {
-        sendError(res, "Project not found", 404);
+        const auto resp = storageErrorResponse(project.error(), "Project not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
     // Leaving a project yourself needs no special power; removing somebody else

+ 55 - 0
src/webserver/api/storage_error.hpp

@@ -0,0 +1,55 @@
+#pragma once
+
+#include <string>
+
+#include "common/error.hpp"
+
+namespace smartbotic::webserver::api {
+
+// Choosing the status for a failed storage call.
+//
+// Every controller here used to answer 404 with "<thing> not found" for any
+// failure at all, which was close enough while the storage layer could only
+// say "it did not work". From database client 2.12.x a failure arrives
+// classified, and flattening it back to 404 throws that away at the last
+// step - and 404 is the one answer that is actively wrong during an outage:
+// it tells the caller the thing does not exist, which is a permanent fact
+// nobody should retry, and the WebUI renders as "not found" over data that
+// is sitting safely in the database.
+//
+// A genuine absence still answers exactly as before, so the 404-not-403
+// convention for permission decisions is untouched: those are not storage
+// failures and do not come through here.
+struct StorageErrorResponse {
+    std::string message;
+    int status;
+};
+
+inline StorageErrorResponse storageErrorResponse(const common::Error& error,
+                                                 const std::string& absent_message) {
+    switch (error.code()) {
+        case common::ErrorCode::Unavailable:
+        case common::ErrorCode::Timeout:
+            // Retryable, and said so: 503 is the only status that invites one.
+            return {"The database could not be reached - the data is still there, "
+                    "please retry (" + error.message() + ")",
+                    503};
+        case common::ErrorCode::ResourceExhausted:
+            return {"The database is over capacity - please retry (" + error.message() + ")", 503};
+        case common::ErrorCode::PermissionDenied:
+        case common::ErrorCode::Unauthenticated:
+            // Deliberately still 404. This service does not confirm the
+            // existence of something the caller may not see.
+            return {absent_message, 404};
+        case common::ErrorCode::DocumentNotFound:
+        case common::ErrorCode::CollectionNotFound:
+        case common::ErrorCode::NotFound:
+            return {absent_message, 404};
+        default:
+            // Something went wrong that is not an absence. Saying "not found"
+            // here is how a broken query came to look like deleted data.
+            return {error.message(), 500};
+    }
+}
+
+} // namespace smartbotic::webserver::api

+ 11 - 5
src/webserver/api/workflow_controller.cpp

@@ -4,6 +4,7 @@
 #include "common/time_utils.hpp"
 #include "common/config_defaults.hpp"
 #include "logging/logger.hpp"
+#include "storage_error.hpp"
 #include <grpcpp/grpcpp.h>
 
 namespace smartbotic::webserver::api {
@@ -180,7 +181,8 @@ bool WorkflowController::loadAllowed(const httplib::Request& req, httplib::Respo
     (void)req;
     auto stored = storage_.get("workflows", id);
     if (stored.failed()) {
-        sendError(res, "Workflow not found", 404);
+        const auto resp = storageErrorResponse(stored.error(), "Workflow not found");
+        sendError(res, resp.message, resp.status);
         return false;
     }
 
@@ -722,7 +724,8 @@ void WorkflowController::deleteWorkflow(const httplib::Request& req, httplib::Re
 
     auto result = storage_.remove("workflows", id);
     if (result.failed()) {
-        sendError(res, "Workflow not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Workflow not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 
@@ -939,7 +942,8 @@ void WorkflowController::getWorkflowVersion(const httplib::Request& req, httplib
 
     auto doc = storage_.getVersion("workflows", id, version);
     if (doc.failed()) {
-        sendError(res, "That version of the workflow is no longer stored", 404);
+        const auto resp = storageErrorResponse(doc.error(), "That version of the workflow is no longer stored");
+        sendError(res, resp.message, resp.status);
         return;
     }
     sendJson(res, doc.value());
@@ -1039,7 +1043,8 @@ void WorkflowController::activateWorkflow(const httplib::Request& req, httplib::
 
     auto result = storage_.update("workflows", id, patch, 0, true);
     if (result.failed()) {
-        sendError(res, "Workflow not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Workflow not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 
@@ -1062,7 +1067,8 @@ void WorkflowController::deactivateWorkflow(const httplib::Request& req, httplib
 
     auto result = storage_.update("workflows", id, {{"active", false}, {"updatedAt", TimeUtils::nowMs()}}, 0, true);
     if (result.failed()) {
-        sendError(res, "Workflow not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Workflow not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 

+ 7 - 3
src/webserver/api/workflow_group_controller.cpp

@@ -1,6 +1,7 @@
 #include "workflow_group_controller.hpp"
 #include "common/uuid.hpp"
 #include "logging/logger.hpp"
+#include "storage_error.hpp"
 
 namespace smartbotic::webserver::api {
 
@@ -80,7 +81,8 @@ bool WorkflowGroupController::loadAllowed(httplib::Response& res, const auth::Au
                                           nlohmann::json& out) {
     auto stored = storage_.get("workflow_groups", id);
     if (stored.failed()) {
-        sendError(res, "Folder not found", 404);
+        const auto resp = storageErrorResponse(stored.error(), "Folder not found");
+        sendError(res, resp.message, resp.status);
         return false;
     }
     const std::string project = auth::AccessControl::projectOf(stored.value());
@@ -383,7 +385,8 @@ void WorkflowGroupController::deleteGroup(const httplib::Request& req, httplib::
 
     auto result = storage_.remove("workflow_groups", id);
     if (result.failed()) {
-        sendError(res, "Group not found", 404);
+        const auto resp = storageErrorResponse(result.error(), "Group not found");
+        sendError(res, resp.message, resp.status);
         return;
     }
 
@@ -431,7 +434,8 @@ void WorkflowGroupController::moveGroup(const httplib::Request& req, httplib::Re
         // Verify group exists
         auto group_result = storage_.get("workflow_groups", id);
         if (group_result.failed()) {
-            sendError(res, "Group not found", 404);
+            const auto resp = storageErrorResponse(group_result.error(), "Group not found");
+            sendError(res, resp.message, resp.status);
             return;
         }
 

+ 16 - 0
src/webserver/retention/retention_service.cpp

@@ -60,6 +60,14 @@ void RetentionService::worker() {
             queue_.pop_front();
         }
 
+        // One job must not be able to end the process. Every storage call below
+        // is supposed to return a Result rather than throw, and the adapter is
+        // written that way - but this runs on its own thread, where an escaping
+        // exception is std::terminate and takes the whole webserver with it, not
+        // just this sweep. A retention pass is also the most deferrable work
+        // here: losing one and logging it beats losing the service.
+        try {
+
         const std::string own = storage::workflowCollectionName(job.workflow_id);
 
         const int64_t executions =
@@ -108,6 +116,14 @@ void RetentionService::worker() {
                 LOG_INFO("Retention: dropped {} for deleted workflow {}", own, job.workflow_id);
             }
         }
+
+        } catch (const std::exception& e) {
+            LOG_ERROR("Retention: workflow {} was not restamped ({}); its data keeps the "
+                      "retention it already had", job.workflow_id, e.what());
+        } catch (...) {
+            LOG_ERROR("Retention: workflow {} was not restamped (unknown error); its data "
+                      "keeps the retention it already had", job.workflow_id);
+        }
     }
 }
 

+ 14 - 1
src/webserver/scheduler/database_watcher.cpp

@@ -63,7 +63,20 @@ void DatabaseWatcher::watch(const std::string& workflow_id,
                           workflow_id, changed_collection, id);
                 return;
             }
-            onEvent(workflow_id, changed_collection, id, event_type, document);
+            // This runs on the client's stream reader thread, and that thread
+            // does not catch: an exception escaping here is std::terminate, so
+            // one malformed event would take the webserver down rather than
+            // skip a trigger. Document is arbitrary JSON from whoever wrote it,
+            // which makes a throw an ordinary possibility rather than a remote one.
+            try {
+                onEvent(workflow_id, changed_collection, id, event_type, document);
+            } catch (const std::exception& e) {
+                LOG_ERROR("Workflow {} not triggered by {}/{}: {}",
+                          workflow_id, changed_collection, id, e.what());
+            } catch (...) {
+                LOG_ERROR("Workflow {} not triggered by {}/{}: unknown error",
+                          workflow_id, changed_collection, id);
+            }
         });
 
     if (!subscription) {

+ 55 - 5
tests/cpp/storage_read_failures_test.cpp

@@ -13,11 +13,22 @@
 // the point: it is the thing the guard exists for, and a test that passed on
 // both versions would not be testing it.
 //
-// Two of the call sites make the "never an exception" half more than tidiness:
-// the scheduler's execution-finished check runs on the scheduler thread, where
-// an escaping exception is std::terminate, and the runner's storage.get()
-// binding is called from QuickJS, which a C++ exception unwinds straight
-// through.
+// Three call sites make the "never an exception" half more than tidiness, all of
+// them threads where an escaping exception is std::terminate rather than a
+// failed request: the scheduler's execution-finished check, the retention
+// worker (which calls listFiles and setFileTtl), and the client's own stream
+// reader thread, which invokes the database watcher's callback and does not
+// catch. The runner's storage.get() binding is a fourth - it is called from
+// QuickJS, which a C++ exception unwinds straight through.
+//
+// The file calls are here for a different reason than the reads: uploadFile,
+// getFileInfo, listFiles and setFileTtl have thrown on a failed status since
+// long before 2.12.4, and were never guarded. 2.12.3 only made uploadFile's
+// refusal more likely and more informative (it refuses mid-stream now, with
+// reason file_too_large or mime_type_not_allowed). The size limit here is
+// 500 MB and no mime allowlist is configured, so those two specific reasons
+// cannot be provoked against this deployment without reconfiguring the
+// daemon - what is checked is the part that applies to every failed status.
 //
 // sources: lib/storage/storage_client.cpp lib/common/error.cpp lib/logging/logger.cpp
 // libs: -lsmartbotic-db-client -lspdlog -lfmt
@@ -114,6 +125,45 @@ int main() {
     expectTransientFailure("getVersion",          [&] { return storage.getVersion("widgets", "w1", 1); });
     expectTransientFailure("listVersions",        [&] { return storage.listVersions("widgets", "w1", 10, 0); });
 
+    // File-store calls. These are not part of the 2.12.4 read change; they
+    // threw all along, and nothing caught them.
+    smartbotic::storage::FileMeta meta;
+    meta.name = "probe.txt";
+    meta.mime_type = "text/plain";
+    meta.file_type = "document";
+    const std::vector<uint8_t> bytes{'h', 'i'};
+
+    expectTransientFailure("uploadFile",   [&] { return storage.uploadFile(bytes, meta, 0); });
+    expectTransientFailure("downloadFile", [&] { return storage.downloadFile("f1"); });
+    expectTransientFailure("getFileInfo",  [&] { return storage.getFileInfo("f1"); });
+    expectTransientFailure("listFiles",    [&] { return storage.listFilesForWorkflow("wf1", 50, 0); });
+
+    // setFileTtl gets its own weaker expectation, deliberately, rather than
+    // being dropped from the list or allowed to loosen the check above.
+    // Upstream returns plain false on any failed status and never throws, and
+    // it has no Failure& overload, so no reason can reach us - the adapter
+    // genuinely cannot tell an outage from an absent file here. What it must
+    // still do is report failure and NOT assert that the file is gone.
+    {
+        ++checks;
+        bool ok_shape = false;
+        try {
+            auto r = storage.setFileTtl("f1", 60000);
+            if (r.ok()) {
+                std::cout << "  FAIL setFileTtl: reported success while the daemon is unreachable\n";
+            } else if (r.error().code() == ErrorCode::DocumentNotFound) {
+                std::cout << "  FAIL setFileTtl: claimed the file is absent, which it cannot know\n";
+            } else {
+                std::cout << "  ok   setFileTtl -> " << codeName(r.error().code())
+                          << " (upstream cannot classify this one; it must not claim absence)\n";
+                ok_shape = true;
+            }
+        } catch (const std::exception& e) {
+            std::cout << "  FAIL setFileTtl: the exception escaped the adapter (" << e.what() << ")\n";
+        }
+        if (!ok_shape) ++failures;
+    }
+
     std::cout << "\n" << (checks - failures) << "/" << checks << " reads reported a classified failure\n";
     if (failures != 0) {
         std::cout << failures << " read(s) still hide an outage\n";