Преглед изворни кода

fix: a failed database read reports an outage, not an absence

Database client 2.12.4 makes a read throw Client::Error on any failed gRPC
status where it used to answer "nothing there". Flagged by the
smartbotic-database session before the upgrade; verified against upstream
6fe5ffa rather than taken on trust.

Not an accidental-upgrade risk here - zeus has no apt or dpkg, the services
run as containers and the image pins the client - so this is a deliberate bump
from 2.12.0-1 to 2.12.4-1, made only once the reads were guarded.

Every read in the adapter now catches and classifies. Two callers need that
for 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. Both already handled a failed Result correctly, so
the single gap was the adapter.

Two of these were already wrong before the upgrade, and are the reason the
change is worth more than compatibility:

- query() caught std::exception and answered CollectionNotFound for all of
  them. Client::Error derives from std::runtime_error, so an outage mid-query
  would have become a definite, unretryable "no such collection" - the exact
  mistake upstream wrote 2.12.4 to stop, reproduced one layer up where the
  catch looked like it was already handling things. downloadFile had the same
  shape. Both now check for NotFound before calling it a miss.

- getCollectionConfig used to answer the DEFAULTS on failure, so an outage
  reported versioning as disabled on a collection that has it on.

listCollections, listCollectionInfos, listIndexes and listViews returned bare
vectors with no error channel, so catching there would only have turned an
outage into "empty". They return Result now, and their three callers handle
it: the runner propagates, the view rebuild leaves an existing view alone
rather than dropping what it cannot see, and the REST listing answers 503
instead of serving an empty list as though the database were empty.

Inside listCollections, collection ownership was decided by
getCollectionInfo(name).ok(). Once a transient failure makes that false, one
timeout silently drops a collection from the database page - the same defect
one level down. Only a definite "not found" excludes a name now.

tests/cpp/storage_read_failures_test.cpp points the adapter at a dead address
and asserts, for ten reads, that nothing escapes, each reports failure, and
the code says transient rather than absent. It is written against the 2.12.4
contract and fails on 2.12.0 - confirmed: 0/10 there, 10/10 after the bump. A
test that passed on both would not have been testing this.

Verified live as well, since the crash risk was the whole point: stopping the
database container made the endpoint answer 503 with the real reason while the
webserver stayed up and /health kept answering 200.

Tests: node suite 103 passed / 0 failed / 2 skipped (the known #106 sd.cpp
auto-unload race), 3 C++ binaries, verify-db-2120.py 4/4 - all on 2.12.4.

CLAUDE.md said to build with `cmake --build build`, which cannot work on zeus,
and to restart via `sv`, which acts on services no longer linked into
/var/service and reports success either way. It also described
SMARTBOTIC_RUNNER_API as only mattering across hosts; the runner is now a
separate container, so without it four cases fail with "Could not connect to
server (http://localhost:8090/...)", which reads like the webserver is down.
All three corrected.

Rollback: smartbotic-automation:pre-2.12.4.
fszontagh пре 1 месец
родитељ
комит
52b91e898b

+ 37 - 31
CLAUDE.md

@@ -10,46 +10,40 @@ SmartBotic is a workflow automation and execution platform with a microservices
 
 ### C++ Backend
 
-The existing `build/` directory is configured with **Ninja**, not Make. Running
-`make` in it prints "Nothing to be done" and builds nothing at all - it does not
-fail, so an edit looks built when it has not been. Always build through cmake,
-which uses whichever generator the directory was configured with:
+**zeus cannot build this project on the host.** It is Void Linux with no apt and
+none of the build dependencies, so `cmake -S . -B build` fails at configure time
+in FindPkgConfig. The build happens in Docker:
 
 ```bash
-# Everything
-cmake --build build -j8
-
-# One target - much faster when only one service changed
-cmake --build build --target smartbotic-webserver -j8
-cmake --build build --target smartbotic-runner -j8
+packaging/build.sh                  # build the .deb and the smartbotic-automation image
+packaging/build.sh --rebuild-base   # also rebuild the build-base image (after a pin bump)
 ```
 
-Configuring a build directory from scratch:
-
-```bash
-# Debug
-cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+The stale `build/` directory and the `./build/smartbotic-*` binaries in it are
+leftovers from September, when the services ran from the host. Do not trust
+them - they are months old and link a client two minor versions behind.
 
-# Release
-cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
+For a quick compile check without producing a deb, build inside the base image:
 
-# With Address Sanitizer
-cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DENABLE_ASAN=ON
+```bash
+docker run --rm -v "$PWD":/src -w /src smartbotic-automation-build-base:debian13 sh -c \
+    'cmake -S . -B /tmp/b -G Ninja -DCMAKE_BUILD_TYPE=Release && cmake --build /tmp/b -j8'
 ```
 
-After building a service, restart it to actually run the new binary. Everything
-runs on **zeus**, which is Void Linux and uses **runit, not systemd**:
+**The services run as Docker containers, not under runit.** `/etc/sv/smartbotic-*`
+still exists but is not linked into `/var/service`, so `sv restart` acts on a
+service that is not the one serving traffic - and says nothing:
 
 ```bash
-sudo sv restart smartbotic-webserver smartbotic-runner
-sudo sv status  smartbotic-webserver smartbotic-runner
-tail -f /var/log/smartbotic-webserver/current
-tail -f /var/log/smartbotic-runner/current
+cd deploy/zeus && docker compose -f docker-compose.services.yml up -d
+docker compose -f docker-compose.services.yml logs -f smartbotic-webserver
+docker ps --filter name=smartbotic
 ```
 
 There is no `systemctl` on zeus at all - it answers "command not found", which
 reads like a typo rather than the wrong init system. The `systemd/user/*.service`
-units in this repo are leftovers from when the services ran on mulan.
+units are leftovers from when the services ran on mulan, and the runit scripts
+are leftovers from the step after that.
 
 ### Tests
 
@@ -61,13 +55,24 @@ python3 scripts/verify-db-2120.py  # database 2.12.0 behaviour, needs the live s
 
 `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. `verify-db-2120.py` covers what a unit test cannot show -
+`// 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 -
 concurrent increments, a watcher ignoring its own writes while still seeing
 other people's, and a refusal arriving classified.
 
-Node tests need the services up. When the runner and webserver are on different
-hosts, a case whose NODE fetches the API needs `SMARTBOTIC_RUNNER_API` set to an
-address the runner can reach - see the `{{API}}` note under Relocating a service.
+Node tests need the services up, and **`SMARTBOTIC_RUNNER_API` is now always
+required**, not just when the two are on different hosts: they are separate
+containers, so the runner's `localhost` is itself and the default leaves four
+cases failing with "Could not connect to server (http://localhost:8090/...)",
+which reads like the webserver is down when it is serving fine.
+
+```bash
+SMARTBOTIC_RUNNER_API=http://smartbotic-webserver:8090 ./scripts/run-node-tests.sh
+```
+
+That host name is the compose service name, the same value the runner already
+gets as `WEBSERVER_ADDRESS`. See the `{{API}}` note under Relocating a service.
 
 ### Frontend (webui/)
 ```bash
@@ -92,7 +97,8 @@ docker ps --filter name=smartbotic-db
 
 # 2. WebServer (HTTP 8090, WebSocket 8091, gRPC 9012 + 9013)
 # 3. Runner (gRPC 9011)
-sudo sv status smartbotic-webserver smartbotic-runner
+# Both are containers from smartbotic-automation:current, not runit services.
+docker ps --filter name=smartbotic
 ```
 
 ### Relocating a service

+ 1 - 1
deploy/zeus/docker-compose.services.yml

@@ -7,7 +7,7 @@
 # its own lifecycle. These two only talk to it.
 #
 # Build the image first (from the repo root):
-#   REPO_PASS=$(grep -oP 'RepoPass:\s*\K.*' /data/smartbotics-deb-repo/.env)
+#   REPO_PASS=$(grep -oP 'RepoPass:\s*\K.*' /data/dev/smartbotics/smartbotics-deb-repo/.env)
 #   docker buildx build -f packaging/Dockerfile.build \
 #     --build-arg BASE_IMAGE=smartbotic-automation-build-base:debian13 \
 #     --build-arg REPO_PASS="$REPO_PASS" \

+ 151 - 25
lib/storage/storage_client.cpp

@@ -91,14 +91,6 @@ bool StorageClient::isConnected() const {
     return impl_ && impl_->client_ && impl_->client_->isConnected();
 }
 
-Result<nlohmann::json> StorageClient::get(const std::string& collection, const std::string& id) {
-    auto opt = impl_->client_->get(collection, id);
-    if (!opt) {
-        return Error(ErrorCode::DocumentNotFound, "Document not found: " + collection + "/" + id);
-    }
-    return *opt;
-}
-
 namespace {
 
 // "Insert failed: credentials" told a reader nothing. 2.12.0 carries a reason,
@@ -108,8 +100,16 @@ std::string describeDbFailure(const char* what,
                               const std::string& collection,
                               const std::string& id,
                               const database::Client::Error& e) {
-    std::string detail = std::string(what) + " failed: " + collection;
-    if (!id.empty()) detail += "/" + id;
+    // An instance-wide read (listCollections, listViews) names no collection,
+    // so the target is omitted rather than left as an empty gap - that read
+    // "listCollections failed: : failed to connect".
+    std::string detail = std::string(what) + " failed";
+    if (!collection.empty()) {
+        detail += ": " + collection;
+        if (!id.empty()) detail += "/" + id;
+    } else if (!id.empty()) {
+        detail += ": " + id;
+    }
     detail += ": ";
     detail += e.what();
 
@@ -131,8 +131,46 @@ std::string describeDbFailure(const char* what,
     return detail;
 }
 
+// From client 2.12.4 a failed READ throws instead of answering "nothing there".
+// 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
+// definite 404 and lost a six-minute ingest.
+//
+// Every read below therefore catches. The exception must not cross this
+// adapter: StorageClient's whole contract is that it returns a Result and never
+// throws, and two of its callers depend on that for 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.
+//
+// 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,
+                  const std::string& collection,
+                  const std::string& id,
+                  const database::Client::Error& e) {
+    return Error(mapDbError(e.code()), describeDbFailure(what, collection, id, e));
+}
+
 } // namespace
 
+Result<nlohmann::json> StorageClient::get(const std::string& collection, const std::string& id) {
+    std::optional<nlohmann::json> opt;
+    try {
+        opt = impl_->client_->get(collection, id);
+    } catch (const Client::Error& e) {
+        return dbReadError("Get", collection, id, e);
+    } catch (const std::exception& e) {
+        return Error(ErrorCode::DatabaseError,
+                     "Get failed: " + collection + "/" + id + ": " + e.what());
+    }
+    if (!opt) {
+        return Error(ErrorCode::DocumentNotFound, "Document not found: " + collection + "/" + id);
+    }
+    return *opt;
+}
+
 Result<std::string> StorageClient::insert(const std::string& collection,
                                           const nlohmann::json& data,
                                           const std::string& id,
@@ -287,9 +325,21 @@ Result<QueryResult> StorageClient::query(const std::string& collection, const Qu
     // instead of returning an empty result, so the miss is not mistaken for
     // an empty collection. Convert it to our Result contract - callers of
     // query() expect an Error, never an exception.
+    // The classification matters as much as the catch. This caught
+    // std::exception and answered CollectionNotFound for every one of them, so
+    // once 2.12.4 made a failed read throw, an outage mid-query reported "no
+    // such collection" - a definite, unretryable answer, which is the very
+    // mistake the upstream change was written to stop. A thrown Client::Error
+    // carries the real code; only an unknown exception is still read as a miss.
     dbc::Client::FindResult fr;
     try {
         fr = impl_->client_->findWithMetrics(collection, up);
+    } catch (const Client::Error& e) {
+        if (e.code() == Client::ErrorCode::NotFound) {
+            return Error(ErrorCode::CollectionNotFound,
+                         "Query failed for '" + collection + "': " + e.what());
+        }
+        return dbReadError("Query", collection, "", e);
     } catch (const std::exception& e) {
         return Error(ErrorCode::CollectionNotFound,
                      "Query failed for '" + collection + "': " + e.what());
@@ -405,21 +455,38 @@ std::shared_ptr<void> StorageClient::subscribeWithActor(
         });
 }
 
-std::vector<CollectionInfo> StorageClient::listCollectionInfos() {
+Result<std::vector<CollectionInfo>> StorageClient::listCollectionInfos() {
+    auto names = listCollections();
+    if (names.failed()) return Error(names.error().code(), names.error().message());
+
     std::vector<CollectionInfo> out;
-    for (const auto& name : listCollections()) {
+    for (const auto& name : names.value()) {
         auto info = getCollectionInfo(name);
         if (info.ok()) {
             // The name as this project knows it, not as the server spelled it.
             info.value().name = name;
             out.push_back(info.value());
+            continue;
+        }
+        // A collection dropped between the listing and this lookup is an
+        // ordinary race and is simply left out. Anything else is not: showing
+        // a short list as though it were complete is how a page comes to say
+        // the data is gone.
+        if (info.error().code() != ErrorCode::CollectionNotFound &&
+            info.error().code() != ErrorCode::DocumentNotFound) {
+            return Error(info.error().code(), info.error().message());
         }
     }
     return out;
 }
 
 Result<CollectionInfo> StorageClient::getCollectionInfo(const std::string& name) {
-    auto upstream = impl_->client_->getCollectionInfo(name);
+    std::optional<database::Client::CollectionInfo> upstream;
+    try {
+        upstream = impl_->client_->getCollectionInfo(name);
+    } catch (const Client::Error& e) {
+        return dbReadError("getCollectionInfo", name, "", e);
+    }
     if (!upstream.has_value()) {
         return Error(ErrorCode::CollectionNotFound, "No such collection: " + name);
     }
@@ -453,7 +520,15 @@ Result<void> StorageClient::configureCollection(const std::string& collection,
 }
 
 Result<CollectionConfig> StorageClient::getCollectionConfig(const std::string& collection) {
-    auto upstream = impl_->client_->getCollectionConfig(collection);
+    // Worth singling out: before 2.12.4 a failed read here answered the
+    // DEFAULTS, so an outage reported versioning as disabled on a collection
+    // that has it on. There was no way for a caller to tell.
+    database::Client::CollectionConfig upstream;
+    try {
+        upstream = impl_->client_->getCollectionConfig(collection);
+    } catch (const Client::Error& e) {
+        return dbReadError("getCollectionConfig", collection, "", e);
+    }
     CollectionConfig cfg;
     cfg.timestamp_precision = upstream.timestampPrecision;
     cfg.versioning_enabled = upstream.versioningEnabled;
@@ -478,9 +553,15 @@ Result<void> StorageClient::dropIndex(const std::string& collection, const std::
     return {};
 }
 
-std::vector<StorageClient::IndexInfo> StorageClient::listIndexes(const std::string& collection) {
+Result<std::vector<StorageClient::IndexInfo>> StorageClient::listIndexes(const std::string& collection) {
+    std::vector<database::Client::IndexDefinition> defs;
+    try {
+        defs = impl_->client_->listIndexes(collection);
+    } catch (const Client::Error& e) {
+        return dbReadError("listIndexes", collection, "", e);
+    }
     std::vector<IndexInfo> out;
-    for (const auto& def : impl_->client_->listIndexes(collection)) {
+    for (const auto& def : defs) {
         out.push_back(IndexInfo{def.field, static_cast<int64_t>(def.distinctValues),
                                 static_cast<int64_t>(def.entries)});
     }
@@ -499,12 +580,19 @@ Result<void> StorageClient::dropCollection(const std::string& name) {
 // Config::project itself, so an unfiltered list both leaks other projects'
 // collections and hands callers names that resolve to nothing when read back.
 // Scope to our own project and strip the prefix, so the names round-trip.
-std::vector<std::string> StorageClient::listCollections() {
+Result<std::vector<std::string>> StorageClient::listCollections() {
     const bool is_default = project_isDefault(impl_->project_);
     const std::string prefix = (is_default ? std::string("default") : impl_->project_) + ":";
 
+    std::vector<std::string> upstream_names;
+    try {
+        upstream_names = impl_->client_->listCollections();
+    } catch (const Client::Error& e) {
+        return dbReadError("listCollections", "", "", e);
+    }
+
     std::vector<std::string> out;
-    for (const auto& name : impl_->client_->listCollections()) {
+    for (const auto& name : upstream_names) {
         if (name.rfind(prefix, 0) == 0) {
             out.push_back(name.substr(prefix.size()));
             continue;
@@ -521,8 +609,21 @@ std::vector<std::string> StorageClient::listCollections() {
         //
         // So the name is asked about rather than guessed at: a lookup is
         // project-scoped, and answers only for a collection that is really ours.
-        if (getCollectionInfo(name).ok()) {
+        //
+        // Only a definite "no such collection" excludes it. Since 2.12.4 this
+        // probe can also fail transiently, and treating that as "not ours"
+        // would quietly shorten the list - one timeout here and a collection
+        // disappears from the database page while it is still there.
+        auto probe = getCollectionInfo(name);
+        if (probe.ok()) {
             out.push_back(name);
+            continue;
+        }
+        if (probe.error().code() != ErrorCode::CollectionNotFound &&
+            probe.error().code() != ErrorCode::DocumentNotFound) {
+            return Error(probe.error().code(),
+                         "Could not tell whether '" + name + "' belongs to this project: " +
+                             probe.error().message());
         }
     }
     (void)is_default;
@@ -535,7 +636,12 @@ std::vector<std::string> StorageClient::listCollections() {
 Result<nlohmann::json> StorageClient::getVersion(const std::string& collection,
                                                  const std::string& id,
                                                  int64_t version) {
-    auto entry = impl_->client_->getDocumentVersion(collection, id, static_cast<uint64_t>(version));
+    std::optional<database::Client::VersionEntry> entry;
+    try {
+        entry = impl_->client_->getDocumentVersion(collection, id, static_cast<uint64_t>(version));
+    } catch (const Client::Error& e) {
+        return dbReadError("getVersion", collection, id, e);
+    }
     if (!entry) return Error(ErrorCode::DocumentNotFound, "Version not found");
     return entry->data;
 }
@@ -544,9 +650,14 @@ Result<VersionListResult> StorageClient::listVersions(const std::string& collect
                                                       const std::string& id,
                                                       int32_t limit,
                                                       int32_t offset) {
-    auto h = impl_->client_->getVersionHistory(collection, id,
-                                               static_cast<uint32_t>(limit),
-                                               static_cast<uint32_t>(offset));
+    database::Client::VersionHistoryResult h;
+    try {
+        h = impl_->client_->getVersionHistory(collection, id,
+                                              static_cast<uint32_t>(limit),
+                                              static_cast<uint32_t>(offset));
+    } catch (const Client::Error& e) {
+        return dbReadError("listVersions", collection, id, e);
+    }
     VersionListResult out;
     out.total_count = static_cast<int64_t>(h.totalCount);
     out.has_more = (offset + static_cast<int32_t>(h.versions.size())) <
@@ -584,9 +695,15 @@ Result<void> StorageClient::dropView(const std::string& name) {
     return {};
 }
 
-std::vector<ViewInfo> StorageClient::listViews() {
+Result<std::vector<ViewInfo>> StorageClient::listViews() {
+    std::vector<database::Client::ViewDefinition> defs;
+    try {
+        defs = impl_->client_->listViews();
+    } catch (const Client::Error& e) {
+        return dbReadError("listViews", "", "", e);
+    }
     std::vector<ViewInfo> out;
-    for (const auto& v : impl_->client_->listViews()) {
+    for (const auto& v : defs) {
         ViewInfo info;
         info.name = v.name;
         info.collection = v.collection;
@@ -635,9 +752,18 @@ Result<std::vector<uint8_t>> StorageClient::downloadFile(const std::string& id)
     // return empty bytes. Without this the exception escapes the adapter and
     // every caller's Result handling is bypassed - and once files carry a TTL,
     // fetching an expired one is an ordinary event rather than a fault.
+    // Same distinction as query(): a missing or expired file is an ordinary
+    // event, but an outage is not, and reporting both as DocumentNotFound told
+    // the caller a file was gone when the daemon was merely unreachable.
     std::vector<uint8_t> bytes;
     try {
         bytes = impl_->client_->downloadFile(id);
+    } catch (const Client::Error& e) {
+        if (e.code() == Client::ErrorCode::NotFound) {
+            return Error(ErrorCode::DocumentNotFound,
+                         "File not found: " + id + " (" + e.what() + ")");
+        }
+        return dbReadError("downloadFile", "files", id, e);
     } catch (const std::exception& e) {
         return Error(ErrorCode::DocumentNotFound,
                      "File not found: " + id + " (" + e.what() + ")");

+ 7 - 4
lib/storage/storage_client.hpp

@@ -221,15 +221,18 @@ public:
         int64_t distinct_values = 0;  // few, over many rows, means the planner will decline it
         int64_t entries = 0;
     };
-    std::vector<IndexInfo> listIndexes(const std::string& collection);
+    common::Result<std::vector<IndexInfo>> listIndexes(const std::string& collection);
 
-    std::vector<std::string> listCollections();
+    // These four report failure rather than answering "empty". From client
+    // 2.12.4 a failed read throws, and an empty list is a valid answer, so a
+    // bare vector could not tell an outage from a database with nothing in it.
+    common::Result<std::vector<std::string>> listCollections();
     common::Result<CollectionInfo> getCollectionInfo(const std::string& name);
 
     // Every collection in this project, with its size and document count.
     // Costs one lookup per candidate name, so it is for an admin screen rather
     // than a hot path.
-    std::vector<CollectionInfo> listCollectionInfos();
+    common::Result<std::vector<CollectionInfo>> listCollectionInfos();
 
     // Atomic increment (database 2.12.0). Adds each number in `deltas` to the
     // document's field in one locked read-modify-write on the server, so two
@@ -293,7 +296,7 @@ public:
 
     common::Result<void> dropView(const std::string& name);
 
-    std::vector<ViewInfo> listViews();
+    common::Result<std::vector<ViewInfo>> listViews();
 
     // Version history can be turned on for a collection that already exists -
     // createCollection cannot, because it fails outright when the collection is

+ 7 - 1
packaging/Dockerfile.base

@@ -26,7 +26,13 @@ ARG REPO_PASS
 # Keep this at the version the daemon runs. The client is backward compatible,
 # so a newer daemon with an older client works - it just cannot use anything
 # the newer one added.
-ARG DB_CLIENT_VERSION=2.12.0-1
+#
+# 2.12.4 is an ERROR-SHAPE change under the same soname: a read whose "nothing
+# there" value is also a valid answer now throws Client::Error on a failed
+# status instead of answering empty. Every read in lib/storage/storage_client.cpp
+# catches it; tests/cpp/storage_read_failures_test.cpp is written against that
+# contract and fails on 2.12.0, so do not lower this without reading it.
+ARG DB_CLIENT_VERSION=2.12.4-1
 COPY packaging/smartbotics-repo.gpg /usr/share/keyrings/smartbotics-repo.gpg
 RUN echo "deb [signed-by=/usr/share/keyrings/smartbotics-repo.gpg] https://repository.smartbotics.ai trixie main" \
         > /etc/apt/sources.list.d/smartbotics.list \

+ 1 - 1
packaging/Dockerfile.build

@@ -95,7 +95,7 @@ ENV DEBIAN_FRONTEND=noninteractive
 # Same version as the builder installed - a runtime library older than the one
 # the binaries were linked against is the kind of mismatch that surfaces as a
 # missing symbol at startup rather than at build time.
-ARG DB_CLIENT_VERSION=2.12.0-1
+ARG DB_CLIENT_VERSION=2.12.4-1
 
 ARG REPO_USER=callerai
 ARG REPO_PASS

+ 4 - 1
scripts/run-cpp-tests.sh

@@ -20,10 +20,13 @@ for test_src in tests/cpp/*_test.cpp; do
     # test does not mean editing this script.
     sources=$(grep -m1 '^// sources:' "$test_src" | sed 's|^// sources:||')
     [ -z "$sources" ] && sources="lib/common/${name%_test}.cpp lib/common/string_utils.cpp"
+    # A test needing more than ssl/crypto names its link flags the same way it
+    # names its sources, so adding one still does not mean editing this script.
+    libs=$(grep -m1 '^// libs:' "$test_src" | sed 's|^// libs:||')
 
     echo "=== $name"
     docker run --rm -v "$PWD":/src -w /src "$IMAGE" sh -c \
-        "g++ -std=c++20 -I lib -o /tmp/$name $test_src $sources -lssl -lcrypto && /tmp/$name"
+        "g++ -std=c++20 -I lib -o /tmp/$name $test_src $sources -lssl -lcrypto $libs && /tmp/$name"
     [ $? -ne 0 ] && fail=$((fail + 1))
 done
 

+ 7 - 1
src/runner/workflow_engine.cpp

@@ -1931,7 +1931,13 @@ NodeExecutionResult WorkflowEngine::executeNode(const WorkflowNode& node,
 
     ctx.storage_list_collections = [this, canReadCollection, own_collection](bool include_system)
         -> common::Result<std::vector<std::string>> {
-        auto all_collections = storage_.listCollections();
+        auto listed = storage_.listCollections();
+        if (listed.failed()) {
+            // Answering with a short list would tell the script the collection
+            // it wants does not exist, which is not what happened.
+            return common::Error(listed.error().code(), listed.error().message());
+        }
+        const auto& all_collections = listed.value();
         std::vector<std::string> accessible;
 
         // A workflow's own storage is offered before it exists - it is created

+ 12 - 1
src/webserver/api/database_controller.cpp

@@ -260,9 +260,20 @@ void DatabaseController::listCollections(const httplib::Request& req, httplib::R
 
     // Names alone meant the page had to ask about each collection separately to
     // show anything about it. The sizes come from the same walk.
+    auto listed = storage_.listCollectionInfos();
+    if (listed.failed()) {
+        // An empty list with HTTP 200 read as "this database has no
+        // collections", and the page said so while the data was untouched.
+        const auto code = listed.error().code();
+        const bool transient = code == common::ErrorCode::Unavailable ||
+                               code == common::ErrorCode::Timeout;
+        sendError(res, listed.error().message(), transient ? 503 : 500);
+        return;
+    }
+
     nlohmann::json details = nlohmann::json::array();
     nlohmann::json names = nlohmann::json::array();
-    for (const auto& info : storage_.listCollectionInfos()) {
+    for (const auto& info : listed.value()) {
         names.push_back(info.name);
         details.push_back({
             {"name", info.name},

+ 10 - 1
src/webserver/webserver_service.cpp

@@ -527,7 +527,16 @@ void WebServerService::ensureExecutionsSummaryView() {
     // rebuilding it costs nothing, and keeping an existing one means the view
     // silently outlives the field list below: after a database recovery the old
     // view served documents that were no longer in the collection at all.
-    for (const auto& view : storage_->listViews()) {
+    auto views = storage_->listViews();
+    if (views.failed()) {
+        // Not knowing whether the view exists is not the same as knowing it
+        // does not. Dropping and recreating blindly on a startup blip would
+        // take a working view away; leaving it is the recoverable choice.
+        LOG_WARN("Could not list views, leaving the executions summary view as it is: {}",
+                 views.error().message());
+        return;
+    }
+    for (const auto& view : views.value()) {
         if (view.name == kExecutionsSummaryView) {
             LOG_INFO("Rebuilding the executions summary view");
             storage_->dropView(kExecutionsSummaryView);

+ 123 - 0
tests/cpp/storage_read_failures_test.cpp

@@ -0,0 +1,123 @@
+// A failed read must arrive as a classified Result, never as a false absence
+// and never as an exception.
+//
+// From libsmartbotic-db-client 2.12.4 a read whose "nothing there" value is
+// also a valid answer throws Client::Error instead of answering empty. Before
+// that, an outage and a genuine absence were the same value: get() gave
+// nullopt, the list reads gave an empty vector and getCollectionConfig() gave
+// the defaults. Upstream changed it because a consumer turned such a blip into
+// a definite 404 and lost a six-minute ingest.
+//
+// This test is deliberately written against the 2.12.4 contract, so it FAILS on
+// 2.12.0 - where these reads answer empty and the adapter cannot tell. That is
+// 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.
+//
+// sources: lib/storage/storage_client.cpp lib/common/error.cpp lib/logging/logger.cpp
+// libs: -lsmartbotic-db-client -lspdlog -lfmt
+
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include "common/error.hpp"
+#include "storage/storage_client.hpp"
+
+using smartbotic::common::ErrorCode;
+using smartbotic::storage::StorageClient;
+using smartbotic::storage::StorageClientConfig;
+
+namespace {
+
+int failures = 0;
+int checks = 0;
+
+const char* codeName(ErrorCode c) {
+    switch (c) {
+        case ErrorCode::DocumentNotFound:   return "DocumentNotFound";
+        case ErrorCode::CollectionNotFound: return "CollectionNotFound";
+        case ErrorCode::Unavailable:        return "Unavailable";
+        case ErrorCode::Timeout:            return "Timeout";
+        case ErrorCode::PermissionDenied:   return "PermissionDenied";
+        case ErrorCode::DatabaseError:      return "DatabaseError";
+        default:                            return "other";
+    }
+}
+
+// An outage is transient and retryable. "Not found" is neither, and telling a
+// caller a document is absent when the daemon is merely unreachable is the
+// defect this whole change is about.
+bool isTransient(ErrorCode c) {
+    return c == ErrorCode::Unavailable || c == ErrorCode::Timeout;
+}
+
+// Every read is checked the same three ways: it must not throw, it must report
+// failure, and the failure must say "transient", not "absent".
+template <typename Fn>
+void expectTransientFailure(const std::string& name, Fn&& fn) {
+    ++checks;
+    try {
+        auto result = fn();
+        if (result.ok()) {
+            std::cout << "  FAIL " << name
+                      << ": reported success while the daemon is unreachable"
+                         " - an outage read as a valid empty answer\n";
+            ++failures;
+            return;
+        }
+        const auto code = result.error().code();
+        if (!isTransient(code)) {
+            std::cout << "  FAIL " << name << ": failed as " << codeName(code)
+                      << ", which says the thing is absent rather than unreachable\n";
+            ++failures;
+            return;
+        }
+        std::cout << "  ok   " << name << " -> " << codeName(code) << "\n";
+    } catch (const std::exception& e) {
+        std::cout << "  FAIL " << name << ": the exception escaped the adapter ("
+                  << e.what() << ") - StorageClient must always return a Result\n";
+        ++failures;
+    } catch (...) {
+        std::cout << "  FAIL " << name << ": a non-std exception escaped the adapter\n";
+        ++failures;
+    }
+}
+
+} // namespace
+
+int main() {
+    StorageClientConfig cfg;
+    // Port 1 refuses immediately, so the suite does not sit on the timeout for
+    // every one of these reads.
+    cfg.address = "127.0.0.1:1";
+    cfg.project = "smartbotic-read-failure-test";
+    cfg.timeout_ms = 1500;
+
+    StorageClient storage(cfg);
+
+    std::cout << "reads against an unreachable daemon:\n";
+
+    expectTransientFailure("get",                 [&] { return storage.get("widgets", "w1"); });
+    expectTransientFailure("query",               [&] { return storage.query("widgets"); });
+    expectTransientFailure("getCollectionInfo",   [&] { return storage.getCollectionInfo("widgets"); });
+    expectTransientFailure("getCollectionConfig", [&] { return storage.getCollectionConfig("widgets"); });
+    expectTransientFailure("listCollections",     [&] { return storage.listCollections(); });
+    expectTransientFailure("listCollectionInfos", [&] { return storage.listCollectionInfos(); });
+    expectTransientFailure("listIndexes",         [&] { return storage.listIndexes("widgets"); });
+    expectTransientFailure("listViews",           [&] { return storage.listViews(); });
+    expectTransientFailure("getVersion",          [&] { return storage.getVersion("widgets", "w1", 1); });
+    expectTransientFailure("listVersions",        [&] { return storage.listVersions("widgets", "w1", 10, 0); });
+
+    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";
+        return 1;
+    }
+    return 0;
+}