Parcourir la source

feat: use what database 2.12.0 added - classified failures, atomic counting, event actors

Three things the 2.12.0 client makes possible, each replacing something this
project was doing by hand.

Failures carry the server's classification. The adapter reported every write
failure as DatabaseError with a message like "Insert failed: credentials", so a
duplicate, a missing relation parent, read-only mode and a permission denial
were one indistinguishable error - and a REST handler could only ever answer
500, including for the one that is plainly a 409. insert and upsert now catch
Client::Error and keep e.code(); remove reads a FailureDetail. The message says
what was objected to: the reason, the constrained fields, the id already
holding them, the relation that blocked a delete. The mapping is a pure
function with its own test, including that an in-band refusal - status OK, no
code, Unknown on the wire - stays DatabaseError rather than being guessed into
something more specific.

consecutiveFailures is counted by the server. Reading the streak and writing
streak+1 loses an increment whenever two runs of one workflow fail at once:
both read N, both write N+1, and a threshold counted that way can be stepped
straight over without ever equalling the limit. The auto-disable decision is
made on the value actually stored, not on what this thread read a moment
earlier. Four concurrent failures now count four.

A database-change trigger no longer feeds itself. A workflow watching a
collection and writing to it retriggered once per write, for as long as it kept
writing. The runner attributes every write a workflow makes and the watcher
skips events it caused, deletes included - removeAs for both cases, because an
empty actor means exactly what plain remove() sends and only removeAs carries
the FailureDetail that can name the relation blocking a delete. Writes by OTHER
workflows still trigger it, which is the whole point of watching.

Both sides go through one actorForWorkflow(), and it has a test for a
two-line function: if the runner and the watcher ever spelled the actor
differently the comparison would simply never match, and the loop would come
back with nothing to show it.

Tested before deploying, as asked. Three C++ binaries, and
scripts/verify-db-2120.py for the parts no unit test can reach. That script
earned its place immediately: the watcher check first reported zero runs, and
the "does not feed itself" half passed BECAUSE of the zero. The cause was in
the log - "No write access to collection" - both test workflows lacked a grant,
so nothing was written, no event fired, and a working watcher looked broken.
Asserting only the absence of a loop would have passed a filter that ignored
everything.

Node suite 103 passed, C++ tests green, all four integration checks pass.
fszontagh il y a 1 mois
Parent
commit
7e14088e31

+ 7 - 0
CLAUDE.md

@@ -56,8 +56,15 @@ units in this repo are leftovers from when the services ran on mulan.
 ```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
 ```
 
+`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 -
+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.

+ 59 - 0
lib/storage/db_error_mapping.hpp

@@ -0,0 +1,59 @@
+#pragma once
+
+#include <smartbotic/database/client.hpp>
+
+#include "common/error.hpp"
+
+namespace smartbotic::storage {
+
+// The database's classification of a failure, carried through instead of
+// flattened.
+//
+// Until 2.12.0 the client dropped it on the way out, so this adapter had
+// nothing to work with and reported every write failure as DatabaseError with a
+// message like "Insert failed: credentials". A duplicate, a missing relation
+// parent, read-only mode and a permission denial were indistinguishable to
+// every caller - which is why a REST handler could only answer 500 to all of
+// them, including the one that is plainly a 409.
+//
+// Pure so it can be tested without a server: see tests/cpp/db_error_mapping_test.cpp.
+inline common::ErrorCode mapDbError(database::Client::ErrorCode code) {
+    using Db = database::Client::ErrorCode;
+    switch (code) {
+        case Db::Ok:
+            return common::ErrorCode::Unknown;   // not a failure; caller should not ask
+        case Db::NotFound:
+            return common::ErrorCode::DocumentNotFound;
+        case Db::AlreadyExists:
+            return common::ErrorCode::AlreadyExists;
+        case Db::PermissionDenied:
+            return common::ErrorCode::PermissionDenied;
+        case Db::FailedPrecondition:
+            // A relation refused the write, or a restricted delete was blocked.
+            // Read-only mode also lands here on the wire; 2.12.0's reason field
+            // separates the two for a caller that needs to know.
+            return common::ErrorCode::FailedPrecondition;
+        case Db::Aborted:
+            return common::ErrorCode::VersionConflict;
+        case Db::InvalidArgument:
+            return common::ErrorCode::InvalidArgument;
+        case Db::ResourceExhausted:
+            return common::ErrorCode::ResourceExhausted;
+        case Db::DeadlineExceeded:
+            return common::ErrorCode::Timeout;
+        case Db::Unavailable:
+            return common::ErrorCode::Unavailable;
+        case Db::Unauthenticated:
+            return common::ErrorCode::Unauthenticated;
+        case Db::Cancelled:
+            return common::ErrorCode::Aborted;
+        case Db::Unknown:
+            // Also what an in-band refusal looks like: status OK, success
+            // false, a message and no code. The message is the only detail.
+            return common::ErrorCode::DatabaseError;
+        default:
+            return common::ErrorCode::DatabaseError;
+    }
+}
+
+} // namespace smartbotic::storage

+ 142 - 18
lib/storage/storage_client.cpp

@@ -4,6 +4,8 @@
 #include <chrono>
 #include <smartbotic/database/client.hpp>
 
+#include "storage/db_error_mapping.hpp"
+
 #include "logging/logger.hpp"
 
 namespace smartbotic::storage {
@@ -11,6 +13,8 @@ namespace smartbotic::storage {
 namespace dbc = smartbotic::database;
 using common::Error;
 using common::ErrorCode;
+
+using database::Client;
 using common::Result;
 
 namespace {
@@ -95,46 +99,123 @@ Result<nlohmann::json> StorageClient::get(const std::string& collection, const s
     return *opt;
 }
 
+namespace {
+
+// "Insert failed: credentials" told a reader nothing. 2.12.0 carries a reason,
+// the fields a constraint covers and the id already holding them, so the
+// message can name the actual objection.
+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;
+    detail += ": ";
+    detail += e.what();
+
+    if (const auto* d = database::Client::errorDetail(e)) {
+        if (!d->reason.empty()) detail += " [" + d->reason + "]";
+        if (!d->fields.empty()) {
+            detail += " field(s): ";
+            for (size_t i = 0; i < d->fields.size(); ++i) {
+                if (i) detail += ", ";
+                detail += d->fields[i];
+            }
+        }
+        if (!d->conflictingId.empty()) detail += " already held by " + d->conflictingId;
+        if (!d->relation.empty()) detail += " via relation " + d->relation;
+        if (d->currentVersion) {
+            detail += " current version " + std::to_string(*d->currentVersion);
+        }
+    }
+    return detail;
+}
+
+} // namespace
+
 Result<std::string> StorageClient::insert(const std::string& collection,
                                           const nlohmann::json& data,
                                           const std::string& id,
-                                          int64_t ttl_ms) {
-    auto new_id = impl_->client_->insert(collection, data, id, msToSec(ttl_ms));
-    if (new_id.empty()) {
-        return Error(ErrorCode::DatabaseError, "Insert failed: " + collection);
+                                          int64_t ttl_ms,
+                                          const std::string& actor) {
+    // insert() throws. Catching Client::Error rather than std::runtime_error
+    // keeps the server's classification - a duplicate reported as
+    // AlreadyExists instead of a generic failure, which is the difference
+    // between a caller answering 409 and answering 500.
+    try {
+        auto new_id = impl_->client_->insert(collection, data, id, msToSec(ttl_ms), actor);
+        if (new_id.empty()) {
+            return Error(ErrorCode::DatabaseError, "Insert failed: " + collection);
+        }
+        return new_id;
+    } catch (const Client::Error& e) {
+        return Error(mapDbError(e.code()), describeDbFailure("Insert", collection, "", e));
+    } catch (const std::exception& e) {
+        return Error(ErrorCode::DatabaseError,
+                     "Insert failed: " + collection + ": " + e.what());
     }
-    return new_id;
 }
 
 Result<std::string> StorageClient::upsert(const std::string& collection,
                                           const nlohmann::json& data,
                                           const std::string& id,
-                                          int64_t ttl_ms) {
-    auto [new_id, is_new] = impl_->client_->upsert(collection, data, id, msToSec(ttl_ms));
-    (void)is_new;
-    if (new_id.empty()) {
-        return Error(ErrorCode::DatabaseError, "Upsert failed: " + collection);
+                                          int64_t ttl_ms,
+                                          const std::string& actor) {
+    try {
+        auto [new_id, is_new] = impl_->client_->upsert(collection, data, id, msToSec(ttl_ms));
+        (void)is_new;
+        if (new_id.empty()) {
+            return Error(ErrorCode::DatabaseError, "Upsert failed: " + collection);
+        }
+        return new_id;
+    } catch (const Client::Error& e) {
+        return Error(mapDbError(e.code()), describeDbFailure("Upsert", collection, id, e));
+    } catch (const std::exception& e) {
+        return Error(ErrorCode::DatabaseError,
+                     "Upsert failed: " + collection + ": " + e.what());
+    }
+}
+
+Result<nlohmann::json> StorageClient::increment(const std::string& collection,
+                                                const std::string& id,
+                                                const nlohmann::json& deltas,
+                                                const std::string& actor) {
+    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 new_id;
+    return *values;
 }
 
 Result<int64_t> StorageClient::update(const std::string& collection,
                                       const std::string& id,
                                       const nlohmann::json& data,
                                       int64_t expected_version,
-                                      bool partial) {
+                                      bool partial,
+                                      const std::string& actor) {
     if (partial) {
-        uint64_t v = impl_->client_->patch(collection, id, data);
+        uint64_t v = impl_->client_->patch(collection, id, data, actor);
         if (v == 0) return Error(ErrorCode::DatabaseError, "Patch failed: " + collection + "/" + id);
         return static_cast<int64_t>(v);
     }
     if (expected_version != 0) {
         bool ok = impl_->client_->updateIfVersion(
-            collection, id, data, static_cast<uint64_t>(expected_version));
+            collection, id, data, static_cast<uint64_t>(expected_version), actor);
         if (!ok) return Error(ErrorCode::VersionConflict, "Version conflict: " + collection + "/" + id);
         return expected_version + 1;
     }
-    bool ok = impl_->client_->update(collection, id, data);
+    bool ok = impl_->client_->update(collection, id, data, actor);
     if (!ok) return Error(ErrorCode::DatabaseError, "Update failed: " + collection + "/" + id);
     // 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.
@@ -154,10 +235,27 @@ Result<int64_t> StorageClient::patchWithTtl(const std::string& collection,
 
 Result<void> StorageClient::remove(const std::string& collection,
                                    const std::string& id,
-                                   int64_t expected_version) {
+                                   int64_t expected_version,
+                                   const std::string& actor) {
     (void)expected_version;  // upstream remove() is unconditional in 1.7.x
-    bool ok = impl_->client_->remove(collection, id);
-    if (!ok) return Error(ErrorCode::DatabaseError, "Remove failed: " + collection + "/" + id);
+
+    // removeAs when the caller said who it is, so the delete's change event
+    // carries the actor too - a watcher that ignores its own writes has to be
+    // able to ignore its own deletes as well, or a workflow that deletes from
+    // the collection it watches still feeds itself.
+    // removeAs for both cases: an empty actor means "carried none", which is
+    // exactly what plain remove() sends, and only removeAs has the full
+    // FailureDetail overload - remove() stops at Failure, which cannot say that
+    // a delete was blocked by a relation or name which one.
+    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 {};
 }
 
@@ -281,6 +379,32 @@ std::shared_ptr<void> StorageClient::subscribe(const std::vector<std::string>& c
         });
 }
 
+std::shared_ptr<void> StorageClient::subscribeWithActor(
+    const std::vector<std::string>& collections,
+    ChangeCallbackWithActor callback) {
+    // Same qualification dance as subscribe() above - the event stream is not
+    // project-scoped, so names are qualified going in and stripped coming out.
+    const bool is_default = project_isDefault(impl_->project_);
+    const std::string prefix = is_default ? std::string() : impl_->project_ + ":";
+
+    std::vector<std::string> qualified;
+    qualified.reserve(collections.size());
+    for (const auto& name : collections) {
+        qualified.push_back(name.find(':') == std::string::npos ? prefix + name : name);
+    }
+
+    return impl_->client_->subscribeEvents(
+        qualified,
+        [callback = std::move(callback), prefix](const database::Client::Event& event) {
+            std::string name = event.collection;
+            if (!prefix.empty() && name.rfind(prefix, 0) == 0) {
+                name = name.substr(prefix.size());
+            }
+            callback(name, event.id, event.eventType,
+                     event.data.value_or(nlohmann::json::object()), event.actor);
+        });
+}
+
 std::vector<CollectionInfo> StorageClient::listCollectionInfos() {
     std::vector<CollectionInfo> out;
     for (const auto& name : listCollections()) {

+ 43 - 4
lib/storage/storage_client.hpp

@@ -143,10 +143,15 @@ public:
 
     common::Result<nlohmann::json> get(const std::string& collection, const std::string& id);
 
+    // `actor` records who caused the write. It is carried on the change event
+    // the server emits, which is how a watcher recognises its own writes - see
+    // subscribeWithActor. Empty means "not attributed", which is what every
+    // caller that does not care gets.
     common::Result<std::string> insert(const std::string& collection,
                                        const nlohmann::json& data,
                                        const std::string& id = "",
-                                       int64_t ttl_ms = 0);
+                                       int64_t ttl_ms = 0,
+                                       const std::string& actor = "");
 
     // Atomic insert-or-replace: swaps the expiration-index entry and installs
     // the new TTL in one locked server-side operation, unlike a remove()
@@ -155,7 +160,8 @@ public:
     common::Result<std::string> upsert(const std::string& collection,
                                        const nlohmann::json& data,
                                        const std::string& id = "",
-                                       int64_t ttl_ms = 0);
+                                       int64_t ttl_ms = 0,
+                                       const std::string& actor = "");
 
     // Returns: the new version on optimistic-lock success (expected_version+1),
     //          the new version on partial/patch success,
@@ -166,7 +172,8 @@ public:
                                    const std::string& id,
                                    const nlohmann::json& data,
                                    int64_t expected_version = 0,
-                                   bool partial = false);
+                                   bool partial = false,
+                                   const std::string& actor = "");
 
     // Merge fields and set the expiry in one server-side step. ttl_ms of 0
     // clears the expiry; pass an empty object to change only the expiry.
@@ -181,7 +188,8 @@ public:
 
     common::Result<void> remove(const std::string& collection,
                                 const std::string& id,
-                                int64_t expected_version = 0);
+                                int64_t expected_version = 0,
+                                const std::string& actor = "");
 
     // Against smartbotic-database >= 2.4.2 an unknown collection or view is
     // reported as ErrorCode::CollectionNotFound rather than an empty result.
@@ -223,6 +231,22 @@ public:
     // than a hot path.
     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
+    // callers incrementing at once cannot lose one of the increments.
+    //
+    // Read-modify-write in our own code is what this replaces: read N, write
+    // N+1, and two concurrent failures both read the same N and both write the
+    // same N+1 - one failure vanishes, and a threshold counted that way can be
+    // stepped over without ever being hit.
+    //
+    // The document must exist; a missing one is DocumentNotFound rather than a
+    // silent create. Returns the incremented fields' new values.
+    common::Result<nlohmann::json> increment(const std::string& collection,
+                                             const std::string& id,
+                                             const nlohmann::json& deltas,
+                                             const std::string& actor = "");
+
     // Server-side change events, so a watcher does not have to poll and keep a
     // timestamp cursor. `document` is empty for a delete.
     //
@@ -236,6 +260,21 @@ public:
     std::shared_ptr<void> subscribe(const std::vector<std::string>& collections,
                                     ChangeCallback callback);
 
+    // The same stream, plus WHO caused each change (database 2.12.0).
+    //
+    // `actor` is whatever the write carried, empty when it carried none and for
+    // an expiry. It is the only way a watcher that writes in response to events
+    // can recognise its own writes: a workflow triggered by a change to a
+    // collection, which then writes to that same collection, otherwise
+    // retriggers itself for as long as it keeps writing.
+    using ChangeCallbackWithActor = std::function<void(const std::string& collection,
+                                                       const std::string& id,
+                                                       const std::string& event_type,
+                                                       const nlohmann::json& document,
+                                                       const std::string& actor)>;
+    std::shared_ptr<void> subscribeWithActor(const std::vector<std::string>& collections,
+                                             ChangeCallbackWithActor callback);
+
     common::Result<nlohmann::json> getVersion(const std::string& collection,
                                               const std::string& id,
                                               int64_t version);

+ 22 - 0
lib/storage/workflow_actor.hpp

@@ -0,0 +1,22 @@
+#pragma once
+
+#include <string>
+
+namespace smartbotic::storage {
+
+// How a workflow's own database writes are attributed.
+//
+// The database carries this string on the change event it emits, so a watcher
+// can tell a write it caused from one it should react to. Both sides have to
+// agree on the spelling, so neither builds it inline: the runner stamps it on
+// every write a workflow makes, and DatabaseWatcher compares against it.
+//
+// Prefixed rather than the bare id so an actor is recognisable in an audit
+// trail - "who changed this document" reads better as wf:<id> than as an
+// unexplained uuid, and it keeps workflow actors from colliding with the user
+// ids that other writes record.
+inline std::string actorForWorkflow(const std::string& workflow_id) {
+    return workflow_id.empty() ? std::string() : "wf:" + workflow_id;
+}
+
+} // namespace smartbotic::storage

+ 224 - 0
scripts/verify-db-2120.py

@@ -0,0 +1,224 @@
+#!/usr/bin/env python3
+"""Integration checks for the database 2.12.0 alignment.
+
+Three things no unit test can show, because each needs a running stack:
+
+  1. consecutiveFailures is counted by the server, so two failures arriving at
+     once both land. Read-modify-write lost one of them.
+  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.
+
+Run against a live webserver + runner:
+
+    python3 scripts/verify-db-2120.py
+"""
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.request
+
+API = os.environ.get("SMARTBOTIC_API", "http://localhost:8090").rstrip("/") + "/api/v1"
+failures = []
+
+
+def call(method, path, token=None, body=None, raw=False):
+    data = json.dumps(body).encode() if body is not None else None
+    req = urllib.request.Request(API + path, data=data, method=method)
+    req.add_header("Content-Type", "application/json")
+    if token:
+        req.add_header("Authorization", "Bearer " + token)
+    try:
+        with urllib.request.urlopen(req, timeout=60) as res:
+            payload = res.read()
+            return json.loads(payload) if payload else {}
+    except urllib.error.HTTPError as e:
+        if raw:
+            return {"__status": e.code, "__body": e.read().decode()[:400]}
+        raise SystemExit(f"{method} {path} failed: {e.code} {e.read().decode()[:300]}")
+
+
+def check(what, ok, detail=""):
+    print(("  ok   " if ok else "  FAIL ") + what)
+    if not ok:
+        failures.append(what)
+        if detail:
+            print("         " + detail)
+
+
+def main():
+    token = call("POST", "/auth/login", body={"username": "admin", "password": "admin"})["accessToken"]
+    project = call("GET", "/projects", token)["projects"][0]["_id"]
+
+    # --- 1. the failure count is the server's, and survives concurrency -------
+    wf = call("POST", "/workflows", token, {
+        "name": "zz verify: failing workflow", "active": False, "projectId": project,
+        "nodes": [
+            {"id": "n1", "name": "Trigger", "type": "click-trigger",
+             "position": {"x": 0, "y": 0}, "config": {}},
+            {"id": "n2", "name": "Boom", "type": "code", "position": {"x": 0, "y": 100},
+             "config": {"code": "throw new Error('planned failure');"}},
+        ],
+        "connections": [{"sourceNodeId": "n1", "sourceOutput": "main",
+                         "targetNodeId": "n2", "targetInput": "data"}],
+    })
+    wf_id = wf.get("id") or wf.get("_id")
+    try:
+        # Fired together on purpose: read-modify-write loses one of these.
+        runs = [call("POST", f"/workflows/{wf_id}/execute", token, {})["executionId"]
+                for _ in range(4)]
+        # A just-dispatched execution is not queryable for a moment - the
+        # record is written after the call returns - so a 404 here means "not
+        # yet", not "gone". raw=True keeps it from aborting the run.
+        def status_of(execution_id):
+            got = call("GET", f"/executions/{execution_id}", token, raw=True)
+            if got.get("__status"):
+                return "pending"
+            return got.get("status") or "pending"
+
+        for _ in range(40):
+            done = [status_of(r) for r in runs]
+            if all(st not in ("running", "pending") for st in done):
+                break
+            time.sleep(2)
+        time.sleep(3)   # the count is written after the run finishes
+        streak = call("GET", f"/workflows/{wf_id}", token).get("consecutiveFailures", 0)
+        check(f"4 concurrent failures all counted (consecutiveFailures={streak})",
+              streak == 4, "read-modify-write would report fewer than 4")
+    finally:
+        call("DELETE", f"/workflows/{wf_id}", token)
+
+    # --- 2. a database-change trigger does not feed itself -------------------
+    # Two workflows, which proves both halves at once:
+    #   A watches the collection AND writes to it. Its own writes must be
+    #     ignored, or it retriggers once per write for as long as it keeps
+    #     writing.
+    #   B only writes to the collection. Its writes are somebody else's and
+    #     must still trigger A - a watcher that ignored everything would pass
+    #     the first half and be useless.
+    watched = "zz_verify_selftrigger"
+
+    def writer(name):
+        return call("POST", "/workflows", token, {
+            "name": name, "active": False, "projectId": project,
+            # Without an explicit grant a workflow may only write its own wf_
+            # collection: "No write access to collection", and then nothing is
+            # written, no event fires, and a watcher that is working perfectly
+            # looks broken.
+            "settings": {"storagePermissions": {"collections": {watched: "read-write"}}},
+            "nodes": [
+                {"id": "t", "name": "Go", "type": "click-trigger",
+                 "position": {"x": 0, "y": 0}, "config": {}},
+                {"id": "w", "name": "Write", "type": "storage-insert",
+                 "position": {"x": 240, "y": 0},
+                 "config": {"collectionSource": "manual", "collectionManual": watched,
+                            "documentData": json.dumps({"from": name})}},
+            ],
+            "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
+                             "targetNodeId": "w", "targetInput": "data"}],
+        })
+
+    watcher = call("POST", "/workflows", token, {
+        "name": "zz verify: watcher that writes back", "active": False, "projectId": project,
+        "settings": {"storagePermissions": {"collections": {watched: "read-write"}}},
+            "nodes": [
+            {"id": "t", "name": "OnChange", "type": "database-change",
+             "position": {"x": 0, "y": 0},
+             "config": {"collection": watched, "eventTypes": ["insert", "update"],
+                        "emitOnFirstRun": False}},
+            {"id": "w", "name": "WriteBack", "type": "storage-insert",
+             "position": {"x": 240, "y": 0},
+             "config": {"collectionSource": "manual", "collectionManual": watched,
+                        "documentData": json.dumps({"from": "the watcher itself"})}},
+        ],
+        "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
+                         "targetNodeId": "w", "targetInput": "data"}],
+    })
+    watcher_id = watcher.get("id") or watcher.get("_id")
+    poker = writer("zz verify: outside writer")
+    poker_id = poker.get("id") or poker.get("_id")
+
+    def runs_of(wf):
+        return len(call("GET", f"/executions?workflowId={wf}&pageSize=50",
+                        token).get("executions", []))
+
+    try:
+        call("POST", f"/workflows/{watcher_id}/activate", token, {})
+        time.sleep(4)          # let the subscription open
+        before = runs_of(watcher_id)
+
+        # Somebody else writes. This one must reach the watcher.
+        call("POST", f"/workflows/{poker_id}/execute", token, {})
+
+        # Long enough that an unbroken loop would be unmistakable: every run
+        # writes once, so the count would climb for as long as we wait.
+        time.sleep(25)
+        grew = runs_of(watcher_id) - before
+
+        check(f"an outside write reached the watcher (ran {grew} time(s))",
+              grew >= 1,
+              "the watcher never fired - it is now ignoring writes it should react to")
+        check(f"the watcher did not feed itself (ran {grew} time(s), not a climbing count)",
+              grew <= 3,
+              "it is still retriggering on its own writes")
+    finally:
+        call("POST", f"/workflows/{watcher_id}/deactivate", token, {})
+        call("DELETE", f"/workflows/{watcher_id}", token)
+        call("DELETE", f"/workflows/{poker_id}", token)
+
+    # --- 3. a duplicate is classified, not flattened -------------------------
+    # Inserting the same document id twice. Before 2.12.0 the client dropped
+    # the server's classification and this arrived as a generic database
+    # error; it must now come back as a conflict, naming the id.
+    dup_collection = "zz_verify_duplicate"
+    dup_wf = call("POST", "/workflows", token, {
+        "name": "zz verify: duplicate insert", "active": False, "projectId": project,
+        "settings": {"storagePermissions": {"collections": {dup_collection: "read-write"}}},
+        "nodes": [
+            {"id": "t", "name": "Go", "type": "click-trigger",
+             "position": {"x": 0, "y": 0}, "config": {}},
+            {"id": "c", "name": "Twice", "type": "code", "position": {"x": 240, "y": 0},
+             "config": {"code": (
+                 "var id = 'fixed-id-for-the-duplicate-check';\n"
+                 "smartbotic.storage.insert('" + dup_collection + "', { n: 1 }, id);\n"
+                 "var second = smartbotic.storage.insert('" + dup_collection + "', { n: 2 }, id);\n"
+                 "return { success: second.success === true, error: String(second.error || '') };")},
+             },
+        ],
+        "connections": [{"sourceNodeId": "t", "sourceOutput": "main",
+                         "targetNodeId": "c", "targetInput": "data"}],
+    })
+    dup_wf_id = dup_wf.get("id") or dup_wf.get("_id")
+    try:
+        run = call("POST", f"/workflows/{dup_wf_id}/execute", token, {})["executionId"]
+        detail = {}
+        for _ in range(30):
+            got = call("GET", f"/executions/{run}", token, raw=True)
+            if not got.get("__status") and got.get("status") not in ("running", "pending", None):
+                detail = got
+                break
+            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}")
+    finally:
+        call("DELETE", f"/workflows/{dup_wf_id}", token)
+
+    print()
+    if failures:
+        print(f"FAILED {len(failures)} check(s)")
+        return 1
+    print("all checks passed")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 15 - 6
src/runner/workflow_engine.cpp

@@ -1,4 +1,6 @@
 #include "workflow_engine.hpp"
+
+#include "storage/workflow_actor.hpp"
 #include "common/uuid.hpp"
 #include "common/time_utils.hpp"
 #include "common/config_defaults.hpp"
@@ -1840,7 +1842,14 @@ NodeExecutionResult WorkflowEngine::executeNode(const WorkflowNode& node,
         return storage_.get(target, id);
     };
 
-    ctx.storage_insert = [this, canWriteCollection, resolveCollection, retention_ttl_ms, own_collection](
+    // Every write a workflow makes is attributed to the workflow, so the change
+    // event carries who caused it. DatabaseWatcher compares against the same
+    // string to avoid retriggering a workflow on its own writes - a workflow
+    // that writes to the collection it watches used to feed itself once per
+    // write. Both sides call actorForWorkflow so the spelling cannot drift.
+    const std::string write_actor = storage::actorForWorkflow(workflow.id);
+
+    ctx.storage_insert = [this, canWriteCollection, resolveCollection, retention_ttl_ms, own_collection, write_actor](
                                 const std::string& collection, const nlohmann::json& data,
                                 const std::string& id, int64_t ttl_ms)
         -> common::Result<std::string> {
@@ -1861,10 +1870,10 @@ NodeExecutionResult WorkflowEngine::executeNode(const WorkflowNode& node,
         // workflow's retention applies, so data written by a node that never
         // heard of retention still ages out.
         const int64_t effective_ttl = ttl_ms > 0 ? ttl_ms : retention_ttl_ms;
-        return storage_.insert(target, data, id, effective_ttl);
+        return storage_.insert(target, data, id, effective_ttl, write_actor);
     };
 
-    ctx.storage_update = [this, canWriteCollection, resolveCollection](
+    ctx.storage_update = [this, canWriteCollection, resolveCollection, write_actor](
                                 const std::string& collection, const std::string& id,
                                 const nlohmann::json& data, int64_t expected_version, bool partial)
         -> common::Result<int64_t> {
@@ -1874,10 +1883,10 @@ NodeExecutionResult WorkflowEngine::executeNode(const WorkflowNode& node,
             return common::Error(common::ErrorCode::PermissionDenied,
                 "No write access to collection: " + target);
         }
-        return storage_.update(target, id, data, expected_version, partial);
+        return storage_.update(target, id, data, expected_version, partial, write_actor);
     };
 
-    ctx.storage_delete = [this, canWriteCollection, resolveCollection](
+    ctx.storage_delete = [this, canWriteCollection, resolveCollection, write_actor](
                                 const std::string& collection, const std::string& id,
                                 int64_t expected_version)
         -> common::Result<void> {
@@ -1887,7 +1896,7 @@ NodeExecutionResult WorkflowEngine::executeNode(const WorkflowNode& node,
             return common::Error(common::ErrorCode::PermissionDenied,
                 "No write access to collection: " + target);
         }
-        return storage_.remove(target, id, expected_version);
+        return storage_.remove(target, id, expected_version, write_actor);
     };
 
     ctx.storage_query = [this, canReadCollection, resolveCollection](

+ 26 - 5
src/webserver/scheduler/database_watcher.cpp

@@ -1,11 +1,15 @@
 #include "database_watcher.hpp"
 
+#include "storage/workflow_actor.hpp"
+
 #include <algorithm>
 
 #include "logging/logger.hpp"
 
 namespace smartbotic::webserver {
 
+using storage::actorForWorkflow;
+
 DatabaseWatcher::DatabaseWatcher(storage::StorageClient& storage) : storage_(storage) {}
 
 DatabaseWatcher::~DatabaseWatcher() {
@@ -36,12 +40,29 @@ void DatabaseWatcher::watch(const std::string& workflow_id,
 
     // Subscribing happens outside the lock: the callback can fire on the
     // client's thread the moment the stream opens, and it takes the same lock.
-    auto subscription = storage_.subscribe(
+    // subscribeWithActor, so the event says who caused the change.
+    //
+    // A workflow triggered by a change to a collection, which then writes to
+    // that same collection, used to retrigger itself - once per write, for as
+    // long as it kept writing. The runner attributes a workflow's own writes
+    // (see actorForWorkflow), so the one event a watcher must ignore is the one
+    // it caused itself.
+    //
+    // Only its OWN writes. A different workflow writing to the same collection
+    // is exactly what this is here to notice.
+    const std::string self = actorForWorkflow(workflow_id);
+    auto subscription = storage_.subscribeWithActor(
         {collection},
-        [this, workflow_id](const std::string& changed_collection,
-                            const std::string& id,
-                            const std::string& event_type,
-                            const nlohmann::json& document) {
+        [this, workflow_id, self](const std::string& changed_collection,
+                                  const std::string& id,
+                                  const std::string& event_type,
+                                  const nlohmann::json& document,
+                                  const std::string& actor) {
+            if (!actor.empty() && actor == self) {
+                LOG_DEBUG("Workflow {} caused the change to {}/{} itself - not retriggering",
+                          workflow_id, changed_collection, id);
+                return;
+            }
             onEvent(workflow_id, changed_collection, id, event_type, document);
         });
 

+ 25 - 3
src/webserver/webserver_service.cpp

@@ -699,13 +699,35 @@ void WebServerService::noteExecutionOutcome(const std::string& workflow_id,
         return;
     }
 
-    const int next = streak + 1;
-    nlohmann::json patch = {{"consecutiveFailures", next}};
+    // Counted by the server, not here. Reading the streak and writing streak+1
+    // loses an increment whenever two runs of the same workflow fail at once:
+    // both read N, both write N+1, and a threshold counted that way can be
+    // stepped straight over without ever equalling the limit.
+    //
+    // The returned value is the authoritative new count, so the decision below
+    // is made on what was actually stored rather than on what this thread
+    // happened to read a moment earlier.
+    int next = streak + 1;
+    auto counted = storage_->increment("workflows", workflow_id, {{"consecutiveFailures", 1}});
+    if (counted.ok()) {
+        next = counted.value().value("consecutiveFailures", next);
+    } else {
+        // A workflow that has never failed may have no such field yet, which
+        // increment treats as 0 and still counts; a genuinely missing document
+        // 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.
+        LOG_WARN("Could not increment the failure count for {} ({}); writing {} directly",
+                 workflow_id, counted.error().message(), next);
+        storage_->update("workflows", workflow_id,
+                         {{"consecutiveFailures", next}}, 0, true);
+    }
+
+    nlohmann::json patch = nlohmann::json::object();
 
     // Counting is worth doing even when nothing is switched off - it is the
     // number someone looks at when asking how long this has been going wrong.
     if (limit <= 0 || next < limit || workflow.value("active", false) != true) {
-        storage_->update("workflows", workflow_id, patch, 0, true);
         return;
     }
 

+ 72 - 0
tests/cpp/db_error_mapping_test.cpp

@@ -0,0 +1,72 @@
+// sources: lib/common/string_utils.cpp
+//
+// The database's failure classification, mapped onto ours.
+//
+// Pure, so it needs no server. The point of the mapping is that a caller can
+// tell a duplicate from a missing relation parent from a denial - before
+// 2.12.0 every one of them arrived as DatabaseError with a message like
+// "Insert failed: credentials", so a REST handler could only ever answer 500.
+
+#include "storage/db_error_mapping.hpp"
+
+#include <iostream>
+#include <string>
+
+using smartbotic::storage::mapDbError;
+using Db = smartbotic::database::Client::ErrorCode;
+using Ours = smartbotic::common::ErrorCode;
+
+namespace {
+
+int failures = 0;
+
+void check(const std::string& what, Ours got, Ours want) {
+    const bool ok = got == want;
+    if (!ok) ++failures;
+    std::cout << (ok ? "  ok   " : "  FAIL ") << what << "\n";
+    if (!ok) {
+        std::cout << "         got:  " << static_cast<int>(got) << "\n";
+        std::cout << "         want: " << static_cast<int>(want) << "\n";
+    }
+}
+
+} // namespace
+
+int main() {
+    // The three that callers actually branch on.
+    check("a unique violation is AlreadyExists, not a generic failure",
+          mapDbError(Db::AlreadyExists), Ours::AlreadyExists);
+    check("a relation refusal is FailedPrecondition",
+          mapDbError(Db::FailedPrecondition), Ours::FailedPrecondition);
+    check("a denial is PermissionDenied",
+          mapDbError(Db::PermissionDenied), Ours::PermissionDenied);
+
+    // A stale version arrives as ABORTED on the wire and has always been
+    // VersionConflict to our callers; the mapping must not change that.
+    check("ABORTED stays VersionConflict", mapDbError(Db::Aborted), Ours::VersionConflict);
+
+    check("NotFound is DocumentNotFound", mapDbError(Db::NotFound), Ours::DocumentNotFound);
+    check("InvalidArgument maps across", mapDbError(Db::InvalidArgument), Ours::InvalidArgument);
+    check("ResourceExhausted maps across",
+          mapDbError(Db::ResourceExhausted), Ours::ResourceExhausted);
+    check("DeadlineExceeded is a Timeout", mapDbError(Db::DeadlineExceeded), Ours::Timeout);
+    check("Unavailable maps across", mapDbError(Db::Unavailable), Ours::Unavailable);
+    check("Unauthenticated maps across",
+          mapDbError(Db::Unauthenticated), Ours::Unauthenticated);
+
+    // An in-band refusal carries no code and arrives as Unknown. It must stay a
+    // database error rather than be guessed into something specific - the
+    // message is the only detail there is.
+    check("Unknown stays DatabaseError", mapDbError(Db::Unknown), Ours::DatabaseError);
+
+    // Codes we have no opinion about must not become a plausible-looking wrong
+    // answer; DatabaseError is the honest default.
+    check("Internal falls back to DatabaseError", mapDbError(Db::Internal), Ours::DatabaseError);
+    check("DataLoss falls back to DatabaseError", mapDbError(Db::DataLoss), Ours::DatabaseError);
+    check("Unimplemented falls back to DatabaseError",
+          mapDbError(Db::Unimplemented), Ours::DatabaseError);
+
+    std::cout << (failures ? "FAILED " + std::to_string(failures) + " check(s)\n"
+                           : "all passed\n");
+    return failures ? 1 : 0;
+}

+ 35 - 0
tests/cpp/workflow_actor_test.cpp

@@ -0,0 +1,35 @@
+// sources: lib/common/string_utils.cpp
+//
+// The spelling of a workflow's write attribution.
+//
+// Trivial on its own, and tested because two places depend on it agreeing: the
+// runner stamps it on every write a workflow makes, and DatabaseWatcher
+// compares against it to avoid retriggering a workflow on its own writes. If
+// the two ever spelled it differently the comparison would simply never match,
+// and the loop it prevents would come back silently.
+
+#include "storage/workflow_actor.hpp"
+
+#include <iostream>
+#include <string>
+
+int main() {
+    int failures = 0;
+    auto check = [&](const std::string& what, const std::string& got, const std::string& want) {
+        const bool ok = got == want;
+        if (!ok) ++failures;
+        std::cout << (ok ? "  ok   " : "  FAIL ") << what << "\n";
+        if (!ok) std::cout << "         got: '" << got << "' want: '" << want << "'\n";
+    };
+
+    check("a workflow id is prefixed",
+          smartbotic::storage::actorForWorkflow("wf_abc123"), "wf:wf_abc123");
+
+    // An empty id must give an empty actor, NOT "wf:" - the watcher skips an
+    // event when the actor matches and is non-empty, and a bare prefix would
+    // match every unattributed write from any workflow.
+    check("an empty id gives no actor", smartbotic::storage::actorForWorkflow(""), "");
+
+    std::cout << (failures ? "FAILED\n" : "all passed\n");
+    return failures ? 1 : 0;
+}