Bläddra i källkod

fix: a write that times out must not be reported as "please retry"

Client 2.13.1 changes what DeadlineExceeded on a WRITE means. The deadline
can expire while the server finishes the write, so it may well have been
applied, and the refusal now carries reason "outcome_unknown". Upstream puts
it plainly: do not map DeadlineExceeded on a write to "retry as-is".

That is exactly what we did. src/webserver/api/storage_error.hpp answered 503
"the data is still there, please retry" for every Timeout, at all 24 call
sites. For a read that is correct and stays. For a write it invited the caller
to repeat a delete that may already have happened.

Two sites genuinely invited it, both storage_.remove(): workflow_controller
and workflow_group_controller. The update()/patch() sites were lossy rather
than dangerous, flattening every failure to a 500 with the reason discarded -
because the 2.12.0 sweep took the FailureDetail overloads for increment() and
remove(), where the structured fields were the obvious draw, and left
update(), patch() and patchWithTtl() on the bare forms. That omission was
invisible until now, when it became the difference between seeing
outcome_unknown and not: patch() is the write path nearly every caller uses.

Moving those three onto the FailureDetail overloads also fixed a latent bug of
ours: a failed updateIfVersion reported VersionConflict unconditionally, even
for a missing document or an unreachable database. Latent only because every
caller passes expected_version = 0 and nothing branches on that code.

The classification lives in the adapter, not the controllers. mapDbError
gained a reason overload where the reason wins over the code, so the single
shared decision in storage_error.hpp stayed the only decision: no call site
was touched, and no future one has to remember which calls are writes.

WriteOutcomeUnknown answers 504, deliberately not 503 or 408 - both invite the
one thing not to do here - and the message carries what the status cannot:
reload before trying again, because repeating it could apply it twice.
DocumentTooLarge answers 422, not 413, since the request body may be tiny and
it is the stored RESULT that would be too large to ever read back.

A DeadlineExceeded with NO reason keeps falling through to Timeout and 503.
That is not an oversight: update() reads before it writes, so a timeout on
that read means the write was never sent. Both branches are pinned by tests so
neither can be collapsed into the other later.

Also in, from the same client:

setFileTtl and deleteFile take the new FailureDetail overloads, so the
three-way hedge ("no such file, already expired, or unreachable; upstream does
not distinguish these") is gone and deleteFile has an error channel at all for
the first time. The retention sweep now logs files it could not restamp and
separates them from files that are simply gone; it previously counted only
successes, so an outage mid-sweep was invisible.

webserver_service.cpp records why the failed-increment fallback must keep
writing an ABSOLUTE value: it is safe under outcome_unknown precisely because
it lands on the same number whether or not the increment took. A second
increment, or a read-then-add, would make a timeout double the count and
switch a workflow off early.

Verified no action needed: connect() is honest now and returns false against a
dead port, but our single call site is non-fatal and not in a loop (5 s worst
case against a 20 s healthcheck start_period), so the count-bounded-loop
failure mode that bit another consumer cannot reach us. Write bodies no longer
store _id/_version/_created_at/_updated_at: all our reads take those from
get()/find() results where the server injects real metadata, and the two sites
writing _id into a body do it after insert() returns, to decorate the HTTP
response.

Tests: node 103 passed / 0 failed / 2 skipped (the known #106 sd.cpp race),
C++ 16/16 on storage_read_failures and 21/21 on db_error_mapping,
verify-db-212x.py 4/4. Live outage probe both directions: an existing
execution answers 503 with the retryable message while the database is
stopped, 404 returns for a bogus id once it is back, and the webserver stayed
up throughout.

Not provable on this deployment: the 504 itself. Stopping the container yields
Unavailable, never DeadlineExceeded, so outcome_unknown cannot be provoked
live - it is covered by the pure mapping test only.

Rollback: smartbotic-automation:pre-2.13.1.
fszontagh 1 månad sedan
förälder
incheckning
07b39e2430

+ 12 - 0
lib/common/error.cpp

@@ -39,6 +39,18 @@ int errorCodeToHttpStatus(ErrorCode code) {
         case ErrorCode::ResourceExhausted:
             return 429;
 
+        // Not 413: the request body may be small - a patch is refused when the
+        // RESULT would be too big to read back. Nothing about the payload tells
+        // the caller that, and retrying it unchanged never helps.
+        case ErrorCode::DocumentTooLarge:
+            return 422;
+
+        // Deliberately not 408 or 503. Both invite the caller to repeat the
+        // request, and the whole point of this code is that repeating a write
+        // whose outcome is unknown is the one thing not to do.
+        case ErrorCode::WriteOutcomeUnknown:
+            return 504;
+
         case ErrorCode::Timeout:
         case ErrorCode::ExecutionTimeout:
         case ErrorCode::ScriptTimeout:

+ 11 - 0
lib/common/error.hpp

@@ -31,6 +31,17 @@ enum class ErrorCode {
     VersionConflict = 2003,
     ValidationError = 2004,
     QueryError = 2005,
+    // A write whose outcome nobody knows. From client 2.13.1 a DeadlineExceeded
+    // on a write carries reason "outcome_unknown": the deadline can expire while
+    // the server finishes the write, so it may well have been applied. This is
+    // deliberately NOT Timeout - Timeout means "it did not happen, repeat it",
+    // and repeating an insert or a delete here duplicates a row or reports a
+    // false not-found.
+    WriteOutcomeUnknown = 2006,
+    // The stored document would be too large to ever read back (client 2.13.1,
+    // reason "document_too_large"). Refused up front, including a patch whose
+    // RESULT would grow the row past the limit. Permanent: retrying is useless.
+    DocumentTooLarge = 2007,
 
     // Auth errors (3xxx)
     AuthError = 3000,

+ 51 - 0
lib/storage/db_error_mapping.hpp

@@ -1,5 +1,7 @@
 #pragma once
 
+#include <string>
+
 #include <smartbotic/database/client.hpp>
 
 #include "common/error.hpp"
@@ -56,4 +58,53 @@ inline common::ErrorCode mapDbError(database::Client::ErrorCode code) {
     }
 }
 
+// The code alone stopped being enough at client 2.13.1.
+//
+// Two refusals now mean something the status code cannot express:
+//
+//   outcome_unknown     DeadlineExceeded on a WRITE. The deadline can expire
+//                       while the server finishes the write, so it may have
+//                       been applied. Mapping this to Timeout would tell the
+//                       caller "it did not happen, send it again" - and a
+//                       repeated insert duplicates a row, a repeated increment
+//                       counts twice, a repeated delete reports a false
+//                       not-found. The client already declines to retry those
+//                       itself; this carries the same restraint outwards.
+//
+//   document_too_large  InvalidArgument for a write whose STORED document
+//                       would exceed what a read could send back. Permanent,
+//                       and not a validation problem with the request body:
+//                       a tiny patch is refused when the result would grow the
+//                       row past the limit.
+//
+// Reason strings, not codes, because that is how upstream carries them; both
+// sit under a code that means something broader on its own.
+//
+// A DeadlineExceeded with NO outcome_unknown is not an oversight and must keep
+// falling through to Timeout. update() reads before it writes, so a timeout on
+// that read means the write was never sent: the outcome IS known, nothing
+// happened, and repeating it is safe. That is the one timeout on a write path
+// where "please retry" is still the right advice.
+inline common::ErrorCode mapDbError(database::Client::ErrorCode code, const std::string& reason) {
+    if (reason == "outcome_unknown") {
+        return common::ErrorCode::WriteOutcomeUnknown;
+    }
+    if (reason == "document_too_large") {
+        return common::ErrorCode::DocumentTooLarge;
+    }
+    return mapDbError(code);
+}
+
+// The reason behind an exception this client threw, or "" when there is none.
+//
+// errorDetail() returns nullptr for an exception the client did not throw, and
+// also for one caught BY VALUE - slicing drops the detail. Every catch in this
+// adapter takes `const Client::Error&` for that reason.
+inline std::string dbFailureReason(const database::Client::Error& e) {
+    if (const auto* detail = database::Client::errorDetail(e)) {
+        return detail->reason;
+    }
+    return {};
+}
+
 } // namespace smartbotic::storage

+ 117 - 45
lib/storage/storage_client.cpp

@@ -131,6 +131,33 @@ std::string describeDbFailure(const char* what,
     return detail;
 }
 
+// One message shape for every write that reports through FailureDetail.
+//
+// increment() and remove() each grew their own copy of this, and update(),
+// patch() and patchWithTtl() had none at all - they said "Patch failed:
+// collection/id" and dropped the reason the server gave. The reason matters
+// most on the two 2.13.1 refusals: "outcome_unknown" is the difference between
+// a write that definitely did not happen and one that may have, and
+// "document_too_large" is the difference between a transient failure and a
+// permanent one.
+std::string describeWriteFailure(const char* what,
+                                 const std::string& collection,
+                                 const std::string& id,
+                                 const database::Client::FailureDetail& failure) {
+    std::string detail = std::string(what) + " failed: " + collection + "/" + id;
+    if (!failure.message.empty()) detail += ": " + failure.message;
+    if (!failure.reason.empty()) detail += " [" + failure.reason + "]";
+    if (!failure.fields.empty()) {
+        detail += " field(s): ";
+        for (size_t i = 0; i < failure.fields.size(); ++i) {
+            if (i) detail += ", ";
+            detail += failure.fields[i];
+        }
+    }
+    if (!failure.relation.empty()) detail += " blocked by relation " + failure.relation;
+    return detail;
+}
+
 // 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.
@@ -152,7 +179,10 @@ Error dbCallError(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));
+    // Reason first, code second: from 2.13.1 two refusals mean something the
+    // code alone cannot say. See mapDbError's reason overload.
+    return Error(mapDbError(e.code(), dbFailureReason(e)),
+                 describeDbFailure(what, collection, id, e));
 }
 
 } // namespace
@@ -189,7 +219,8 @@ Result<std::string> StorageClient::insert(const std::string& collection,
         }
         return new_id;
     } catch (const Client::Error& e) {
-        return Error(mapDbError(e.code()), describeDbFailure("Insert", collection, "", e));
+        return Error(mapDbError(e.code(), dbFailureReason(e)),
+                     describeDbFailure("Insert", collection, "", e));
     } catch (const std::exception& e) {
         return Error(ErrorCode::DatabaseError,
                      "Insert failed: " + collection + ": " + e.what());
@@ -209,7 +240,8 @@ Result<std::string> StorageClient::upsert(const std::string& collection,
         }
         return new_id;
     } catch (const Client::Error& e) {
-        return Error(mapDbError(e.code()), describeDbFailure("Upsert", collection, id, e));
+        return Error(mapDbError(e.code(), dbFailureReason(e)),
+                     describeDbFailure("Upsert", collection, id, e));
     } catch (const std::exception& e) {
         return Error(ErrorCode::DatabaseError,
                      "Upsert failed: " + collection + ": " + e.what());
@@ -223,17 +255,8 @@ Result<nlohmann::json> StorageClient::increment(const std::string& collection,
     database::Client::FailureDetail failure;
     auto values = impl_->client_->increment(collection, id, deltas, failure, actor);
     if (!values) {
-        std::string detail = "Increment failed: " + collection + "/" + id;
-        if (!failure.message.empty()) detail += ": " + failure.message;
-        if (!failure.reason.empty()) detail += " [" + failure.reason + "]";
-        if (!failure.fields.empty()) {
-            detail += " field(s): ";
-            for (size_t i = 0; i < failure.fields.size(); ++i) {
-                if (i) detail += ", ";
-                detail += failure.fields[i];
-            }
-        }
-        return Error(mapDbError(failure.code), detail);
+        return Error(mapDbError(failure.code, failure.reason),
+                     describeWriteFailure("Increment", collection, id, failure));
     }
     return *values;
 }
@@ -244,19 +267,42 @@ Result<int64_t> StorageClient::update(const std::string& collection,
                                       int64_t expected_version,
                                       bool partial,
                                       const std::string& actor) {
+    // All three branches take the FailureDetail overload (2.11.4/2.12.0). They
+    // used to take the bare forms and flatten every failure to DatabaseError -
+    // or, worse, to a specific code that was often wrong: a failed
+    // updateIfVersion was reported as a version conflict even when the
+    // document was simply missing or the database was unreachable.
+    //
+    // That also kept reason strings out of reach, and from 2.13.1 the reason is
+    // the only thing that distinguishes a write which may have been applied
+    // (outcome_unknown) from one that definitely was not. patch() is the write
+    // path most callers here use, so without this the new classification could
+    // never surface.
     if (partial) {
-        uint64_t v = impl_->client_->patch(collection, id, data, actor);
-        if (v == 0) return Error(ErrorCode::DatabaseError, "Patch failed: " + collection + "/" + id);
+        database::Client::FailureDetail failure;
+        const uint64_t v = impl_->client_->patch(collection, id, data, failure, actor);
+        if (v == 0) {
+            return Error(mapDbError(failure.code, failure.reason),
+                         describeWriteFailure("Patch", collection, id, failure));
+        }
         return static_cast<int64_t>(v);
     }
     if (expected_version != 0) {
-        bool ok = impl_->client_->updateIfVersion(
-            collection, id, data, static_cast<uint64_t>(expected_version), actor);
-        if (!ok) return Error(ErrorCode::VersionConflict, "Version conflict: " + collection + "/" + id);
+        database::Client::FailureDetail failure;
+        const bool ok = impl_->client_->updateIfVersion(
+            collection, id, data, static_cast<uint64_t>(expected_version), failure, actor);
+        if (!ok) {
+            return Error(mapDbError(failure.code, failure.reason),
+                         describeWriteFailure("Conditional update", collection, id, failure));
+        }
         return expected_version + 1;
     }
-    bool ok = impl_->client_->update(collection, id, data, actor);
-    if (!ok) return Error(ErrorCode::DatabaseError, "Update failed: " + collection + "/" + id);
+    database::Client::FailureDetail failure;
+    const bool ok = impl_->client_->update(collection, id, data, failure, actor);
+    if (!ok) {
+        return Error(mapDbError(failure.code, failure.reason),
+                     describeWriteFailure("Update", collection, id, failure));
+    }
     // Upstream plain update() returns bool only; the new version is not exposed.
     // Use -1 to signal "version unknown" so callers cannot mistake it for version 0.
     return -1;
@@ -266,9 +312,12 @@ Result<int64_t> StorageClient::patchWithTtl(const std::string& collection,
                                             const std::string& id,
                                             const nlohmann::json& fields,
                                             int64_t ttl_ms) {
-    uint64_t version = impl_->client_->patchWithTtl(collection, id, fields, msToSec(ttl_ms));
+    database::Client::FailureDetail failure;
+    const uint64_t version =
+        impl_->client_->patchWithTtl(collection, id, fields, msToSec(ttl_ms), failure);
     if (version == 0) {
-        return Error(ErrorCode::DatabaseError, "Patch with TTL failed: " + collection + "/" + id);
+        return Error(mapDbError(failure.code, failure.reason),
+                     describeWriteFailure("Patch with TTL", collection, id, failure));
     }
     return static_cast<int64_t>(version);
 }
@@ -290,11 +339,8 @@ Result<void> StorageClient::remove(const std::string& collection,
     database::Client::FailureDetail failure;
     const bool ok = impl_->client_->removeAs(collection, id, actor, failure);
     if (!ok) {
-        std::string detail = "Remove failed: " + collection + "/" + id;
-        if (!failure.message.empty()) detail += ": " + failure.message;
-        if (!failure.reason.empty()) detail += " [" + failure.reason + "]";
-        if (!failure.relation.empty()) detail += " blocked by relation " + failure.relation;
-        return Error(mapDbError(failure.code), detail);
+        return Error(mapDbError(failure.code, failure.reason),
+                     describeWriteFailure("Remove", collection, id, failure));
     }
     return {};
 }
@@ -846,35 +892,61 @@ Result<std::vector<FileInfo>> StorageClient::listFilesForWorkflow(const std::str
 }
 
 Result<void> StorageClient::setFileTtl(const std::string& id, int64_t ttl_ms) {
-    // 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.
+    // From client 2.13.1 this call can finally say WHY it failed.
     //
-    // 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.
+    // It used to return a bare false for every failed status with no channel to
+    // report a reason through, so this returned a message naming all three
+    // possibilities at once - "no such file, already expired, or the database
+    // could not be reached; upstream does not distinguish these". That hedge was
+    // honest but useless: the retention worker could not tell a file it should
+    // stop restamping from a database it should wait for. The FailureDetail
+    // overload separates them, so the hedge is gone.
+    //
+    // NotFound still covers two cases upstream treats as one - the file is not
+    // in this project, or its TTL already elapsed - but both mean the same
+    // thing to a caller: there is nothing left to restamp.
+    database::Client::FailureDetail failure;
     bool ok = false;
     try {
-        ok = impl_->client_->setFileTtl(id, msToSec(ttl_ms));
+        ok = impl_->client_->setFileTtl(id, msToSec(ttl_ms), failure);
     } catch (const Client::Error& e) {
         return dbCallError("setFileTtl", "files", id, e);
+    } catch (const std::exception& e) {
+        return Error(ErrorCode::DatabaseError,
+                     "setFileTtl failed: files/" + id + ": " + e.what());
     }
     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");
+        if (failure.code == Client::ErrorCode::NotFound) {
+            return Error(ErrorCode::DocumentNotFound,
+                         "No file " + id + " to set an expiry on - it is not in this project, "
+                         "or it has already expired");
+        }
+        return Error(mapDbError(failure.code, failure.reason),
+                     describeWriteFailure("setFileTtl", "files", id, failure));
     }
     return {};
 }
 
 Result<void> StorageClient::deleteFile(const std::string& id) {
-    if (!impl_->client_->deleteFile(id)) {
-        return Error(ErrorCode::DatabaseError, "Failed to delete file: " + id);
+    // Had no error channel at all before 2.13.1: a bare false became
+    // DatabaseError "Failed to delete file", so an unreachable database and a
+    // file that was never there read identically.
+    database::Client::FailureDetail failure;
+    bool ok = false;
+    try {
+        ok = impl_->client_->deleteFile(id, failure);
+    } catch (const Client::Error& e) {
+        return dbCallError("deleteFile", "files", id, e);
+    } catch (const std::exception& e) {
+        return Error(ErrorCode::DatabaseError,
+                     "deleteFile failed: files/" + id + ": " + e.what());
+    }
+    if (!ok) {
+        if (failure.code == Client::ErrorCode::NotFound) {
+            return Error(ErrorCode::DocumentNotFound, "No file " + id + " to delete");
+        }
+        return Error(mapDbError(failure.code, failure.reason),
+                     describeWriteFailure("deleteFile", "files", id, failure));
     }
     return {};
 }

+ 15 - 6
packaging/Dockerfile.base

@@ -27,12 +27,21 @@ ARG REPO_PASS
 # so a newer daemon with an older client works - it just cannot use anything
 # the newer one added.
 #
-# 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
+# Two ERROR-SHAPE changes live under this unchanged soname, so a symbol or ABI
+# check reports "no consumer impact" and is wrong both times:
+#
+# 2.12.4 - 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.
+# 2.13.1 - DeadlineExceeded on a WRITE no longer means the write failed; it
+#   carries reason "outcome_unknown", because the deadline can expire while the
+#   server finishes it. We map that to ErrorCode::WriteOutcomeUnknown and
+#   answer 504 WITHOUT inviting a retry, since repeating such a write can apply
+#   it twice. Lowering the pin silently restores "please retry" on those.
+#
+# tests/cpp/storage_read_failures_test.cpp is written against both contracts and
+# fails on anything older, so do not lower this without reading it.
+ARG DB_CLIENT_VERSION=2.13.1-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.4-1
+ARG DB_CLIENT_VERSION=2.13.1-1
 
 ARG REPO_USER=callerai
 ARG REPO_PASS

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

@@ -36,6 +36,24 @@ inline StorageErrorResponse storageErrorResponse(const common::Error& error,
                     503};
         case common::ErrorCode::ResourceExhausted:
             return {"The database is over capacity - please retry (" + error.message() + ")", 503};
+
+        // A write that timed out may well have been applied: from client 2.13.1
+        // the deadline can expire while the server finishes it. This is the one
+        // failure where "please retry" is the wrong advice - repeating it can
+        // delete something twice or report a conflict that is really our own
+        // earlier write. So it does not get a 503, and it does not claim the
+        // data is still there, because nobody knows.
+        case common::ErrorCode::WriteOutcomeUnknown:
+            return {"The database did not answer in time and this change may or may not "
+                    "have been applied - reload before trying again, because repeating it "
+                    "could apply it twice (" + error.message() + ")",
+                    504};
+
+        // Permanent, and a retry of the identical request can only fail again.
+        case common::ErrorCode::DocumentTooLarge:
+            return {"This change was refused because the stored record would be too large "
+                    "to read back (" + error.message() + ")",
+                    422};
         case common::ErrorCode::PermissionDenied:
         case common::ErrorCode::Unauthenticated:
             // Deliberately still 404. This service does not confirm the

+ 28 - 3
src/webserver/retention/retention_service.cpp

@@ -86,16 +86,41 @@ void RetentionService::worker() {
         // generous with a file whose document has already gone is the harmless
         // direction - the sweeper takes it either way.
         int64_t files = 0;
+        int64_t files_unreachable = 0;
         auto owned = storage_.listFilesForWorkflow(job.workflow_id);
         if (owned.ok()) {
             for (const auto& file : owned.value()) {
                 if (stopping_) break;
-                if (storage_.setFileTtl(file.id, job.ttl_seconds * 1000).ok()) files++;
+                auto stamped = storage_.setFileTtl(file.id, job.ttl_seconds * 1000);
+                if (stamped.ok()) {
+                    files++;
+                    continue;
+                }
+                // Until client 2.13.1 this could only say "it did not work", so
+                // the count of successes was the whole story and a database
+                // blip looked exactly like a file that had already expired.
+                // A file that is gone needs no restamping and is not worth a
+                // line; one we could not reach keeps its old, shorter expiry,
+                // which is the harmless direction but not a non-event - it is
+                // the reason a later sweep finds fewer files than it should.
+                if (stamped.error().code() != common::ErrorCode::DocumentNotFound) {
+                    files_unreachable++;
+                    LOG_WARN("Retention: file {} of workflow {} kept its existing expiry ({})",
+                             file.id, job.workflow_id, stamped.error().message());
+                }
             }
         }
 
-        LOG_INFO("Retention: workflow {} restamped to {}s - {} executions, {} documents, {} files",
-                 job.workflow_id, job.ttl_seconds, executions, documents, files);
+        if (files_unreachable > 0) {
+            LOG_WARN("Retention: workflow {} restamped to {}s - {} executions, {} documents, "
+                     "{} files, and {} files NOT restamped",
+                     job.workflow_id, job.ttl_seconds, executions, documents, files,
+                     files_unreachable);
+        } else {
+            LOG_INFO("Retention: workflow {} restamped to {}s - {} executions, {} documents, "
+                     "{} files",
+                     job.workflow_id, job.ttl_seconds, executions, documents, files);
+        }
 
         if (job.drop_collection_after) {
             // The documents are not gone yet - they expire on their own shortly.

+ 9 - 0
src/webserver/webserver_service.cpp

@@ -726,6 +726,15 @@ void WebServerService::noteExecutionOutcome(const std::string& workflow_id,
         // is the only real failure here, and then there is nothing to switch
         // off either. Fall back to the old write so the count is not simply
         // lost.
+        //
+        // This fallback must keep writing an ABSOLUTE value. Client 2.13.1
+        // declines to retry a timed-out increment, because repeating one counts
+        // twice, and reports WriteOutcomeUnknown instead - the increment may
+        // already have been applied. Storing `next` outright is safe either
+        // way: it lands on the same number whether or not the increment took.
+        // Turning this into a second increment, or into a read-then-add, is the
+        // one change that would make a timeout double the count and switch a
+        // workflow off early.
         LOG_WARN("Could not increment the failure count for {} ({}); writing {} directly",
                  workflow_id, counted.error().message(), next);
         storage_->update("workflows", workflow_id,

+ 54 - 1
tests/cpp/db_error_mapping_test.cpp

@@ -1,4 +1,4 @@
-// sources: lib/common/string_utils.cpp
+// sources: lib/common/string_utils.cpp lib/common/error.cpp
 //
 // The database's failure classification, mapped onto ours.
 //
@@ -12,6 +12,7 @@
 #include <iostream>
 #include <string>
 
+using smartbotic::common::errorCodeToHttpStatus;
 using smartbotic::storage::mapDbError;
 using Db = smartbotic::database::Client::ErrorCode;
 using Ours = smartbotic::common::ErrorCode;
@@ -30,6 +31,16 @@ void check(const std::string& what, Ours got, Ours want) {
     }
 }
 
+void checkStatus(const std::string& what, int got, int want) {
+    const bool ok = got == want;
+    if (!ok) ++failures;
+    std::cout << (ok ? "  ok   " : "  FAIL ") << what << "\n";
+    if (!ok) {
+        std::cout << "         got:  " << got << "\n";
+        std::cout << "         want: " << want << "\n";
+    }
+}
+
 } // namespace
 
 int main() {
@@ -66,6 +77,48 @@ int main() {
     check("Unimplemented falls back to DatabaseError",
           mapDbError(Db::Unimplemented), Ours::DatabaseError);
 
+    // --- the reason overload (client 2.13.1) ---
+    //
+    // Two refusals mean something the status code cannot express, so the reason
+    // has to win over the code. These cannot be provoked against an unreachable
+    // daemon (that answers Unavailable), which is exactly why they are checked
+    // here instead of in storage_read_failures_test.cpp.
+
+    // The important one. DeadlineExceeded on a write no longer means "it did
+    // not happen": the deadline can expire while the server finishes the write.
+    // If this ever maps back to Timeout, the controllers resume telling callers
+    // to repeat a write that may already have been applied - a duplicated row,
+    // a doubled increment or a false not-found.
+    check("outcome_unknown beats DeadlineExceeded",
+          mapDbError(Db::DeadlineExceeded, "outcome_unknown"), Ours::WriteOutcomeUnknown);
+
+    // Permanent, and under a code that normally means "fix the request".
+    check("document_too_large beats InvalidArgument",
+          mapDbError(Db::InvalidArgument, "document_too_large"), Ours::DocumentTooLarge);
+
+    // A reason the mapping has no opinion about must not disturb the code.
+    check("an unknown reason leaves the code alone",
+          mapDbError(Db::Unavailable, "something_new"), Ours::Unavailable);
+    // Not an oversight: update() reads before it writes, and a timeout on that
+    // read means the write was never sent. The outcome is known - nothing
+    // happened - so this must stay Timeout and keep answering 503 "please
+    // retry", which is the correct advice for exactly this case.
+    check("a write timeout with no reason stays a retryable Timeout",
+          mapDbError(Db::DeadlineExceeded, ""), Ours::Timeout);
+
+    // message_too_large is a SIZE refusal from gRPC itself, not a document that
+    // is too big to store - it stays ResourceExhausted so a rate limit and a
+    // too-large message keep answering 429, as they did before.
+    check("message_too_large stays ResourceExhausted",
+          mapDbError(Db::ResourceExhausted, "message_too_large"), Ours::ResourceExhausted);
+
+    // And the statuses the two new codes must reach, since the whole point is
+    // the advice the caller gets.
+    checkStatus("WriteOutcomeUnknown is a 504, not a 503",
+                errorCodeToHttpStatus(Ours::WriteOutcomeUnknown), 504);
+    checkStatus("DocumentTooLarge is a 422, not a 500",
+                errorCodeToHttpStatus(Ours::DocumentTooLarge), 422);
+
     std::cout << (failures ? "FAILED " + std::to_string(failures) + " check(s)\n"
                            : "all passed\n");
     return failures ? 1 : 0;

+ 34 - 28
tests/cpp/storage_read_failures_test.cpp

@@ -30,6 +30,21 @@
 // cannot be provoked against this deployment without reconfiguring the
 // daemon - what is checked is the part that applies to every failed status.
 //
+// setFileTtl and deleteFile were the two exceptions until client 2.13.1. They
+// returned a bare false for every failed status with no channel to report a
+// reason, so setFileTtl carried a hedge naming three possibilities at once and
+// deleteFile had no error channel at all. 2.13.1 gave both a FailureDetail
+// overload, so they are now held to the same standard as everything else here
+// and no longer get their own weaker case.
+//
+// Those two overloads arrived in 2.13.0, so on 2.12.4 and earlier this file no
+// longer COMPILES rather than failing an assertion - a harder failure than the
+// read contract above, which compiles on 2.12.0 and fails at runtime. The
+// outcome_unknown classification that 2.13.1 added cannot be provoked from
+// here at all (an unreachable daemon answers Unavailable, never
+// DeadlineExceeded), which is why it is asserted in
+// tests/cpp/db_error_mapping_test.cpp instead.
+//
 // sources: lib/storage/storage_client.cpp lib/common/error.cpp lib/logging/logger.cpp
 // libs: -lsmartbotic-db-client -lspdlog -lfmt
 
@@ -57,6 +72,8 @@ const char* codeName(ErrorCode c) {
         case ErrorCode::Timeout:            return "Timeout";
         case ErrorCode::PermissionDenied:   return "PermissionDenied";
         case ErrorCode::DatabaseError:      return "DatabaseError";
+        case ErrorCode::WriteOutcomeUnknown: return "WriteOutcomeUnknown";
+        case ErrorCode::DocumentTooLarge:   return "DocumentTooLarge";
         default:                            return "other";
     }
 }
@@ -65,7 +82,13 @@ const char* codeName(ErrorCode c) {
 // 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;
+    // WriteOutcomeUnknown belongs here for the write calls below. It is not an
+    // absence either - it says the write may or may not have landed - and a
+    // write that times out under load reports it rather than Timeout. Against
+    // port 1 the answer is Unavailable, so this is not what makes the checks
+    // pass; it is here so a slower environment does not fail them spuriously.
+    return c == ErrorCode::Unavailable || c == ErrorCode::Timeout ||
+           c == ErrorCode::WriteOutcomeUnknown;
 }
 
 // Every read is checked the same three ways: it must not throw, it must report
@@ -138,35 +161,18 @@ int main() {
     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;
-    }
+    // setFileTtl and deleteFile are ordinary cases from 2.13.1 on. They used to
+    // need a hand-written weaker check because upstream gave them no way to
+    // report a reason; the FailureDetail overloads removed that excuse, so they
+    // are held to the same "must not claim absence" rule as every call above.
+    // If either of these starts failing as DocumentNotFound, the adapter has
+    // gone back to asserting something it cannot know.
+    expectTransientFailure("setFileTtl",  [&] { return storage.setFileTtl("f1", 60000); });
+    expectTransientFailure("deleteFile",  [&] { return storage.deleteFile("f1"); });
 
-    std::cout << "\n" << (checks - failures) << "/" << checks << " reads reported a classified failure\n";
+    std::cout << "\n" << (checks - failures) << "/" << checks << " calls reported a classified failure\n";
     if (failures != 0) {
-        std::cout << failures << " read(s) still hide an outage\n";
+        std::cout << failures << " call(s) still hide an outage\n";
         return 1;
     }
     return 0;