Эх сурвалжийг харах

fix: 2.13.1 - a row must stay readable, a timed-out write may have happened, connect() connects

The three items 2.13.0 left open.

1. Write-time size guard. A row could grow past the gRPC send limit through
   small patches (smartbotic-vectorapi: insert 60 MiB, patch +20/+10/+10) and
   then never be read or exported. A write whose stored body would exceed the
   send limit less 256 KB is now refused with INVALID_ARGUMENT, reason
   document_too_large: insert/update/upsert/batch bodies before parsing, and
   the MERGED result of a patch before anything is mutated.

2. A timed-out write. The client retried every write on DEADLINE_EXCEEDED,
   but the deadline can expire while the server finishes the write, so a
   retry repeated a write that happened (duplicate rows, double increments,
   false AlreadyExists / version conflict / not-found). DEADLINE_EXCEEDED is
   now retried only for idempotent writes (plain patch, upsert with an id),
   every such failure carries reason outcome_unknown, and writes get a
   size-scaled deadline (timeoutMs + 1 s per 4 MiB).

3. update() retried every refusal, not only version conflicts (read-only,
   memory pressure, size, outage) and logged them as version conflicts. It
   now re-reads only on a conflict.

4. connect() returned true and logged "connected" without opening anything,
   even against a dead port (reported by smartbotic). It now waits up to
   timeoutMs for a real connection and returns false when unreachable; the
   client stays usable. isConnected() counts IDLE/CONNECTING only after a
   successful attempt.

Tests: test_read_failures frozen phase separates retry from none by timing
and checks outcome_unknown; connect checks in every phase; test_export runs
its later phases at a 2 MB send limit and checks the guard. Each part
reverted alone fails a test (2/4/3/3/2); update()'s conflict-only retry is
not pinned (same answer either way). ctest 24/24, e2e 18/18. ABI unchanged.
fszontagh 1 сар өмнө
parent
commit
399634864b

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.13.0
+2.13.1

+ 13 - 2
client/include/smartbotic/database/client.hpp

@@ -288,12 +288,23 @@ public:
     Client& operator=(const Client&) = delete;
 
     /**
-     * Connect to the database service.
+     * Connect to the database service: set up the channel and wait up to
+     * Config::timeoutMs for it to connect.
+     *
+     * v2.13.1: returns false when the server cannot be reached within that
+     * time. Before 2.13.1 it returned true without ever opening a connection,
+     * so it said "connected" even against a dead port. On false the client is
+     * still usable: gRPC keeps reconnecting on later calls, and those calls
+     * report Unavailable while the server is down. Note that with the server
+     * down this call now takes up to timeoutMs instead of returning at once.
      */
     bool connect();
 
     /**
-     * Check if connected.
+     * The channel's last known state: false after a failed connection attempt
+     * or disconnect(). Not a live probe - an idle channel to a server that has
+     * since gone away still answers true until a call fails. For "is the
+     * database answering right now" use healthCheck().
      */
     [[nodiscard]] bool isConnected() const;
 

+ 103 - 22
client/src/client.cpp

@@ -186,6 +186,11 @@ struct FailureSink {
     }
     // An in-band refusal (status OK, success=false): the code is in the
     // response from a 2.12.0+ server, Unknown from an older one.
+    // Copy a reason a nested call already recorded (v2.13.1).
+    void copy(const Client::FailureDetail& d) const {
+        if (failure) { failure->code = d.code; failure->message = d.message; }
+        if (detail) *detail = d;
+    }
     void recordInBand(int32_t errorCode, const std::string& message,
                       const std::string& detailJson) const {
         record(errorCode != 0 ? static_cast<Client::ErrorCode>(errorCode) : Client::ErrorCode::Unknown,
@@ -221,9 +226,20 @@ nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) {
 // writes (insert with explicit ID, updateIfVersion, upsert, remove, patch).
 // All other codes (INVALID_ARGUMENT, FAILED_PRECONDITION, NOT_FOUND, ...) are
 // final — no retry.
-bool retryableStatus(const grpc::Status& s) {
+//
+// v2.13.1 - DEADLINE_EXCEEDED is retried only for an IDEMPOTENT write. The
+// deadline can expire while the server finishes the write (seen by
+// smartbotic-vectorapi on large patches: every one reported failure and had
+// been applied), so a retry repeats a write that already happened: an id-less
+// insert duplicates the row, an increment counts twice, and an insert with an
+// id, a conditional write or a delete reports a false AlreadyExists / version
+// conflict / not-found. Those are not retried; the failure carries reason
+// outcome_unknown (see outcomeUnknownDetail). UNAVAILABLE and
+// RESOURCE_EXHAUSTED still retry: the server did not act on the request.
+bool retryableStatus(const grpc::Status& s, bool idempotent) {
     switch (s.error_code()) {
-        case grpc::StatusCode::DEADLINE_EXCEEDED:  // server queued behind eviction/WAL
+        case grpc::StatusCode::DEADLINE_EXCEEDED:  // may have been applied
+            return idempotent;
         case grpc::StatusCode::RESOURCE_EXHAUSTED: // admission control or gRPC concurrency cap
         case grpc::StatusCode::UNAVAILABLE:        // transient connection issue
             return true;
@@ -232,6 +248,16 @@ bool retryableStatus(const grpc::Status& s) {
     }
 }
 
+// v2.13.1 - a write that ended in DEADLINE_EXCEEDED may or may not have been
+// applied; say so in the reason, so a caller checks before redoing it instead
+// of reading "the write failed". Leaves a server-supplied detail alone.
+std::string outcomeUnknownDetail(const grpc::Status& s, const std::string& detailJson) {
+    if (s.error_code() == grpc::StatusCode::DEADLINE_EXCEEDED && detailJson.empty()) {
+        return R"({"reason":"outcome_unknown"})";
+    }
+    return detailJson;
+}
+
 // Exponential backoff with jitter. attempt=0 => baseMs; attempt=1 => baseMs*2; ...
 uint32_t computeBackoffMs(uint32_t baseMs, uint32_t attempt, uint32_t capMs, double jitterPct) {
     uint64_t exp = static_cast<uint64_t>(baseMs) << attempt;
@@ -337,6 +363,21 @@ public:
 
             const char* scheme = config_.tls_enabled ? "tls" : "plaintext";
             const char* authed = config_.auth_token.empty() ? "no-auth" : "bearer-auth";
+            // v2.13.1 - actually try. Creating a gRPC channel opens nothing, so
+            // this used to return true and log "connected" against a dead port
+            // (reported by smartbotic): connect() and isConnected() were not
+            // reachability checks at all. Now it waits up to timeoutMs for the
+            // channel to connect. On failure the client stays usable - gRPC
+            // keeps reconnecting on later calls - but the answer is honest.
+            const bool reachable = channel_->WaitForConnected(
+                std::chrono::system_clock::now() + std::chrono::milliseconds(config_.timeoutMs));
+            reached_ = reachable;
+            if (!reachable) {
+                spdlog::warn("Database client could not reach {} ({}, {}) within {} ms; "
+                             "it will keep trying on later calls",
+                             config_.address, scheme, authed, config_.timeoutMs);
+                return false;
+            }
             spdlog::info("Database client connected to {} ({}, {})",
                          config_.address, scheme, authed);
             return true;
@@ -412,6 +453,7 @@ public:
 
     void disconnect() {
         connected_ = false;
+        reached_ = false;
         stub_.reset();
         channel_.reset();
     }
@@ -420,11 +462,13 @@ public:
         if (!connected_ || !channel_) {
             return false;
         }
-        // Check if channel is in a usable state (not failed or shutdown)
+        // READY is connected. IDLE (no calls for a while) and CONNECTING
+        // count only if the last connection attempt succeeded (v2.13.1):
+        // against a frozen server the kernel accepts the TCP connection and
+        // the channel sits in CONNECTING forever, which used to read as true.
         auto state = channel_->GetState(false);
-        return state == GRPC_CHANNEL_READY ||
-               state == GRPC_CHANNEL_IDLE ||
-               state == GRPC_CHANNEL_CONNECTING;
+        if (state == GRPC_CHANNEL_READY) return true;
+        return reached_ && (state == GRPC_CHANNEL_IDLE || state == GRPC_CHANNEL_CONNECTING);
     }
 
     // ===== Document Operations =====
@@ -450,11 +494,11 @@ public:
         std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
-            setDeadline(context);
+            setWriteDeadline(context, request.ByteSizeLong());   // v2.13.1
             response.Clear();
             status = stub_->Insert(&context, request, &response);
             detailJson = trailerDetail(context);   // v2.12.0
-            if (status.ok() || !retryableStatus(status)) {
+            if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
                 break;
             }
             if (attempt < config_.writeRetries) {
@@ -467,6 +511,7 @@ public:
                 std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
             }
         }
+        detailJson = outcomeUnknownDetail(status, detailJson);   // v2.13.1
         if (!status.ok()) {
             spdlog::error("Client::insert failed after retries: {}", status.error_message());
             throwStatus(status, status.error_message(), detailJson);
@@ -553,9 +598,26 @@ public:
             // Attempt version-checked update. Each attempt overwrites
             // failureOut, so what the caller reads is the LAST attempt's
             // reason, and a success leaves it clean.
-            if (updateIfVersion(collection, id, cleanData, version, actor, failureOut)) {
+            Client::FailureDetail attemptFailure;
+            if (updateIfVersion(collection, id, cleanData, version, actor, &attemptFailure)) {
+                failureOut.reset();
                 return true;
             }
+            failureOut.copy(attemptFailure);
+            // v2.13.1 - only a version conflict (another writer between our
+            // get() and this write) is worth another round. Every other
+            // refusal - read-only, memory pressure, a document too large, an
+            // outage - was retried here too and then logged as "version
+            // conflicts", though no retry could change the answer.
+            // A pre-2.12.0 server reports the conflict in-band with no code
+            // (Unknown) and the text "Version conflict".
+            const bool conflict =
+                attemptFailure.code == Client::ErrorCode::Aborted ||
+                (attemptFailure.code == Client::ErrorCode::Unknown &&
+                 attemptFailure.message.find("ersion conflict") != std::string::npos);
+            if (!conflict) {
+                return false;
+            }
 
             // Version conflict — another client wrote between our get() and update
             if (attempt < config_.maxRetries) {
@@ -588,11 +650,11 @@ public:
         std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
-            setDeadline(context);
+            setWriteDeadline(context, request.ByteSizeLong());   // v2.13.1
             response.Clear();
             status = stub_->Update(&context, request, &response);
             detailJson = trailerDetail(context);   // v2.12.0
-            if (status.ok() || !retryableStatus(status)) {
+            if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
                 break;
             }
             if (attempt < config_.writeRetries) {
@@ -605,6 +667,7 @@ public:
                 std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
             }
         }
+        detailJson = outcomeUnknownDetail(status, detailJson);   // v2.13.1
         if (!status.ok()) {
             spdlog::error("Client::updateIfVersion failed after retries: {}", status.error_message());
             failureOut.record(status, detailJson);
@@ -648,11 +711,11 @@ public:
         std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
-            setDeadline(context);
+            setWriteDeadline(context, request.ByteSizeLong());   // v2.13.1
             response.Clear();
             status = stub_->PatchDocument(&context, request, &response);
             detailJson = trailerDetail(context);   // v2.12.0
-            if (status.ok() || !retryableStatus(status)) {
+            if (status.ok() || !retryableStatus(status, /*idempotent=*/!request.has_expected_version() && request.increments_json().empty())) {
                 break;
             }
             if (attempt < config_.writeRetries) {
@@ -665,6 +728,7 @@ public:
                 std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
             }
         }
+        detailJson = outcomeUnknownDetail(status, detailJson);   // v2.13.1
         if (!status.ok()) {
             spdlog::error("Client::patch failed after retries: {}", status.error_message());
             failureOut.record(status, detailJson);
@@ -706,11 +770,11 @@ public:
         std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
-            setDeadline(context);
+            setWriteDeadline(context, request.ByteSizeLong());   // v2.13.1
             response.Clear();
             status = stub_->Upsert(&context, request, &response);
             detailJson = trailerDetail(context);   // v2.12.0
-            if (status.ok() || !retryableStatus(status)) {
+            if (status.ok() || !retryableStatus(status, /*idempotent=*/!id.empty())) {
                 break;
             }
             if (attempt < config_.writeRetries) {
@@ -723,6 +787,7 @@ public:
                 std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
             }
         }
+        detailJson = outcomeUnknownDetail(status, detailJson);   // v2.13.1
         if (!status.ok()) {
             spdlog::error("Client::upsert failed after retries: {}", status.error_message());
             throwStatus(status, status.error_message(), detailJson);
@@ -753,11 +818,11 @@ public:
         std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
-            setDeadline(context);
+            setWriteDeadline(context, request.ByteSizeLong());   // v2.13.1
             response.Clear();
             status = stub_->Delete(&context, request, &response);
             detailJson = trailerDetail(context);   // v2.12.0
-            if (status.ok() || !retryableStatus(status)) {
+            if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) {
                 break;
             }
             if (attempt < config_.writeRetries) {
@@ -770,6 +835,7 @@ public:
                 std::this_thread::sleep_for(std::chrono::milliseconds(backoffMs));
             }
         }
+        detailJson = outcomeUnknownDetail(status, detailJson);   // v2.13.1
         if (!status.ok()) {
             spdlog::error("Client::remove failed after retries: {}", status.error_message());
             if (errorOut != nullptr) *errorOut = status.error_message();
@@ -812,22 +878,24 @@ public:
         smartbotic::databasepb::BatchDeleteResponse response;
         grpc::Status status;
         std::string detailJson;
-        // Retried like the other deletes: deleting an id twice is harmless, and
-        // a retry after a lost reply reports the ids the first attempt removed
-        // as not found - which is why deletedIds is "what THIS call removed".
+        // v2.13.1 - retried only when the server cannot have acted (UNAVAILABLE,
+        // RESOURCE_EXHAUSTED). After a DEADLINE_EXCEEDED the first attempt may
+        // have deleted the ids, and a retry would report them as not found, so
+        // that failure is returned with reason outcome_unknown instead.
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
-            setDeadline(context);
+            setWriteDeadline(context, request.ByteSizeLong());   // v2.13.1
             response.Clear();
             status = stub_->BatchDelete(&context, request, &response);
             detailJson = trailerDetail(context);
-            if (status.ok() || !retryableStatus(status)) break;
+            if (status.ok() || !retryableStatus(status, /*idempotent=*/false)) break;
             if (attempt < config_.writeRetries) {
                 std::this_thread::sleep_for(std::chrono::milliseconds(computeBackoffMs(
                     config_.writeRetryBackoffMs, attempt,
                     config_.writeRetryMaxBackoffMs, config_.writeRetryJitter)));
             }
         }
+        detailJson = outcomeUnknownDetail(status, detailJson);   // v2.13.1
         if (!status.ok()) {
             spdlog::error("Client::removeManyAs failed: {}", status.error_message());
             failureOut.record(status, detailJson);
@@ -2842,6 +2910,18 @@ private:
         attachAuth(context);
     }
 
+    // v2.13.1 - a write's deadline grows with its size: timeoutMs plus one
+    // second per 4 MiB sent. A 20 MiB patch on a 60 MiB row legitimately takes
+    // longer than a small write, and a fixed deadline made it time out while the
+    // server completed it - the shape that produced "failed" writes that had
+    // been applied.
+    void setWriteDeadline(grpc::ClientContext& context, size_t requestBytes) {
+        const auto extraMs = static_cast<uint64_t>(requestBytes / (4u * 1024 * 1024)) * 1000;
+        context.set_deadline(std::chrono::system_clock::now() +
+                             std::chrono::milliseconds(config_.timeoutMs + extraMs));
+        attachAuth(context);
+    }
+
     // v2.4 — attach the bearer-token authorization metadata if configured.
     // Use this on contexts that set their own deadline (streams,
     // long-running ops) so the auth metadata still lands.
@@ -2855,6 +2935,7 @@ private:
     std::shared_ptr<grpc::Channel> channel_;
     std::unique_ptr<smartbotic::databasepb::DatabaseService::Stub> stub_;
     std::atomic<bool> connected_{false};
+    std::atomic<bool> reached_{false};   // v2.13.1 - the last connect() attempt succeeded
 };
 
 // ===== Client Public Interface Implementation =====

+ 14 - 3
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.13.0** (see `VERSION`). Last reviewed: 2026-10-08.
+**Released version: 2.13.1** (see `VERSION`). Last reviewed: 2026-10-08.
 
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
@@ -56,7 +56,7 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.13.0. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.13.1. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -97,6 +97,10 @@ detail and the failure modes.
   a document and its vector commit in one LMDB transaction; write bodies can no
   longer store the six read-metadata names; `deleteFile`/`setFileTtl` take a
   `Failure&`; a throwing event handler no longer terminates the process (2.13.0)
+- Writes cannot leave an unreadable row (`document_too_large`, incl. patch
+  growth); a timed-out write says `outcome_unknown` and is retried only when
+  idempotent; `update()` retries only version conflicts; `connect()` reports an
+  unreachable server (2.13.1)
 - Conditional partial update (`patchIfVersion`) and atomic increment
   (`increment`) (2.12.0)
 - Event provenance: the actor on every `DatabaseEvent`, `removeAs()`,
@@ -307,7 +311,7 @@ A write landing inside the outage fails after the client's short retry window.
 Seen here as the runner's heartbeat being refused for a few seconds; it
 recovered by itself, exactly as it does during the nightly backup stop.
 
-### 5b-3. Open after the 2.13.0 pre-release run (smartbotic-vectorapi, 2026-10-08)
+### 5b-3. ~~Open after the 2.13.0 pre-release run~~ - both CLOSED in 2.13.1
 
 - **A row can grow past the gRPC send limit through `patch`.** Measured on the
   scratch server with send = receive = 100 MB: insert 60 MiB, then patch +20,
@@ -322,6 +326,13 @@ recovered by itself, exactly as it does during the nightly backup stop.
   an idempotent patch, wrong for `increment` or an id-less insert. Options: a
   deadline scaled by request size, not retrying `DEADLINE_EXCEEDED` for
   non-idempotent writes, or a request id the server de-duplicates.
+- **Closed in 2.13.1:** a write whose stored row would exceed the send limit
+  (less 256 KB) is refused (`document_too_large`), including the RESULT of a
+  patch; a write that timed out is retried only when idempotent and otherwise
+  reports reason `outcome_unknown`, with a size-scaled deadline. Also closed:
+  `connect()` now waits for a real connection (reported by smartbotic). A
+  server-side request id that de-duplicates retries remains possible future
+  work; it is not needed for correctness now.
 
 ### 5b-2. Open after the v2.11.4 consumer feedback round
 

+ 41 - 0
docs/integration-guide.md

@@ -356,6 +356,47 @@ release, each one a real bug it already had:
   thread. 2.13.0 logs and drops that one event and keeps the stream; a handler
   should still catch its own errors, since a dropped event is lost.
 
+#### A write that times out may have happened (2.13.1+)
+
+A `DeadlineExceeded` on a write does not mean "the write failed": the deadline
+can expire while the server finishes it. Since 2.13.1 such a failure carries
+reason **`outcome_unknown`** (`Failure`/`FailureDetail`, or `errorDetail(e)` for
+`insert`/`upsert`), and the client only retries a write after a timeout when
+repeating it cannot change or misreport the result:
+
+| Write | Retried after `DeadlineExceeded`? |
+|-------|-----------------------------------|
+| `patch` (no increments, no expected version), `upsert` with an id | yes - idempotent |
+| `insert`, `upsert` without an id, `increment`, `patchIfVersion`, `updateIfVersion`, `update`'s inner write, `remove`/`removeAs`/`removeManyAs` | no - a repeat would duplicate a row, count twice, or report a false AlreadyExists / version conflict / not-found |
+
+`Unavailable` and `ResourceExhausted` are still retried: the server did not act.
+**Do not map `DeadlineExceeded` on a write to "retry as-is".** With
+`outcome_unknown`, read the row first (or write under a fixed id) and decide.
+Large writes also get a longer deadline: `timeoutMs` plus one second per 4 MiB.
+
+`update()` re-reads and retries only on a version conflict; before 2.13.1 it
+retried every refusal (read-only, memory pressure, size) and then logged
+"version conflicts".
+
+#### A row must stay readable (2.13.1+)
+
+A write that would store a document no read could send back is refused with
+`InvalidArgument`, reason **`document_too_large`**: an `insert`/`update`/`upsert`/
+batch body, or the RESULT of a `patch`. The limit is the server's
+`max_send_message_size_mb` less 256 KB. Before 2.13.1 a row could grow past it
+one small patch at a time and then fail every `get` with `message_too_large`.
+Rows already that large stay unreadable; the export names them `row_too_large`.
+
+#### `connect()` actually connects (2.13.1+)
+
+`connect()` waits up to `timeoutMs` for the channel to connect and returns
+**false** when the server cannot be reached. Before 2.13.1 it returned true
+without opening anything, even against a dead port. On false the client is
+still usable (gRPC keeps reconnecting; calls report `Unavailable` meanwhile).
+With the server down, `connect()` now takes up to `timeoutMs`. `isConnected()`
+is the channel's last known state, not a live probe: use `healthCheck()` for
+"is the database answering now".
+
 #### The full reason: `FailureDetail` (2.12.0+)
 
 A status code alone is ambiguous - `FailedPrecondition` means a missing parent,

+ 30 - 0
service/src/database_grpc_impl.cpp

@@ -420,6 +420,9 @@ grpc::Status DatabaseGrpcImpl::Insert(
             "cannot write to view '" + request->collection() + "': views are read-only");
     }
     try {
+        if (auto st = refuseUnreadableBody(context, request->data().size()); !st.ok()) {
+            return st;   // v2.13.1
+        }
         nlohmann::json data = smartbotic::db::parse_to_nlohmann(request->data());
         stripReservedFields(data);  // v2.13.0 - never store read metadata
         if (auto st = rejectMaskedWrite(data, dec.mask); !st.ok()) return st;
@@ -629,6 +632,9 @@ grpc::Status DatabaseGrpcImpl::Update(
                             "cannot write to view '" + request->collection() + "': views are read-only");
     }
     try {
+        if (auto st = refuseUnreadableBody(context, request->data().size()); !st.ok()) {
+            return st;   // v2.13.1
+        }
         nlohmann::json data = smartbotic::db::parse_to_nlohmann(request->data());
         stripReservedFields(data);  // v2.13.0 - never store read metadata
 
@@ -779,6 +785,10 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
                                             {"fields", nlohmann::json::array({refusal.field})}});
                 return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, refusal.message);
             }
+            if (refusal.kind == Kind::TooLarge) {   // v2.13.1
+                attachErrorDetail(context, {{"reason", "document_too_large"}});
+                return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, refusal.message);
+            }
             return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
                                 "not_found", "Document not found");
         }
@@ -836,6 +846,9 @@ grpc::Status DatabaseGrpcImpl::Upsert(
             "cannot write to view '" + request->collection() + "': views are read-only");
     }
     try {
+        if (auto st = refuseUnreadableBody(context, request->data().size()); !st.ok()) {
+            return st;   // v2.13.1
+        }
         nlohmann::json data = smartbotic::db::parse_to_nlohmann(request->data());
         stripReservedFields(data);  // v2.13.0 - never store read metadata
         if (auto st = rejectMaskedWrite(data, dec.mask); !st.ok()) return st;
@@ -1298,6 +1311,10 @@ grpc::Status DatabaseGrpcImpl::BatchInsert(
 
     for (const auto& item : request->items()) {
         try {
+            if (const size_t lim = store_.maxDocumentBytes(); lim > 0 && item.data().size() > lim) {
+                ++errorCount;   // v2.13.1 - it could never be read back
+                continue;
+            }
             nlohmann::json data = smartbotic::db::parse_to_nlohmann(item.data());
             stripReservedFields(data);  // v2.13.0 - never store read metadata
 
@@ -1837,6 +1854,19 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
     }
 }
 
+// v2.13.1 - a write whose body is larger than any read can send back would
+// create a row nothing can read or export. Refused before parsing: the length
+// is already known, and parsing a body that will be refused is wasted work.
+grpc::Status DatabaseGrpcImpl::refuseUnreadableBody(grpc::ServerContext* context,
+                                                    size_t bodyBytes) {
+    const size_t limit = store_.maxDocumentBytes();
+    if (limit == 0 || bodyBytes <= limit) return grpc::Status::OK;
+    attachErrorDetail(context, {{"reason", "document_too_large"}});
+    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+        "document is " + std::to_string(bodyBytes) + " bytes, more than a read can send back (" +
+        std::to_string(limit) + "); store large data as a file or split it");
+}
+
 // v2.13.0 - ExportCollection. The contract is in the proto, above
 // ExportRequest. The parts that are decisions rather than plumbing:
 //   - one collection, never a project, gated as an ordinary READ of it;

+ 1 - 0
service/src/database_grpc_impl.hpp

@@ -462,6 +462,7 @@ private:
     // Convert internal types to proto types
     static pb::Document toProto(const Document& doc);
     void attachStoredVector(pb::Document& protoDoc, const std::string& collection);   // v2.13.0
+    grpc::Status refuseUnreadableBody(grpc::ServerContext* context, size_t bodyBytes);   // v2.13.1
     static Document fromProto(const pb::Document& proto);
     static pb::CollectionInfo toProtoCollInfo(const struct CollectionInfo& info);
     static pb::DocumentVersionEntry toProtoVersionEntry(const DocumentVersion& ver);

+ 9 - 0
service/src/database_service.cpp

@@ -1551,6 +1551,15 @@ void DatabaseService::setupComponents() {
         config_.grpc.maxConcurrentFileStreams);
     storageImpl_->setMaxSendBytes(
         static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024);   // v2.13.0
+    // v2.13.1 - a stored row must stay readable: the largest body a write may
+    // leave behind is the send limit less room for metadata and a vector sent
+    // alongside (16 KB at dimension 4096). Enforced on insert/update/upsert/
+    // batch bodies and on the RESULT of a patch.
+    {
+        constexpr size_t kReadMargin = 256 * 1024;
+        const size_t send = static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024;
+        store_->setMaxDocumentBytes(send > 2 * kReadMargin ? send - kReadMargin : send / 2);
+    }
     replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
         *store_, *replication_, *persistence_
     );

+ 20 - 0
service/src/memory_store.cpp

@@ -1517,6 +1517,26 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
         if (incrementedOut) *incrementedOut = std::move(newValues);
     }
 
+    // v2.13.1 - refuse a patch whose RESULT could not be read back. Every
+    // request can be small while the row grows past the send limit one patch
+    // at a time (found by smartbotic-vectorapi: insert 60 MiB, patch +20/+10/+10,
+    // then get failed and the row could not be exported). Measured as the JSON
+    // text a read sends, before anything is mutated, so a refusal leaves no
+    // trace - the same rule the increments above follow.
+    if (const size_t limit = maxDocumentBytes_.load(); limit > 0) {
+        const size_t bytes = smartbotic::db::doc_binary::to_json_text(
+            smartbotic::db::doc_binary::encode(merged)).size();
+        if (bytes > limit) {
+            if (refusal) {
+                refusal->kind = PatchRefusal::Kind::TooLarge;
+                refusal->message = "the patched document would be " + std::to_string(bytes) +
+                    " bytes, more than a read can send back (" + std::to_string(limit) +
+                    "); store large data as a file or split it";
+            }
+            return 0;
+        }
+    }
+
     // Track memory change (old size)
     uint64_t oldSize = estimateDocumentSize(it->second);
 

+ 12 - 1
service/src/memory_store.hpp

@@ -348,6 +348,12 @@ public:
      */
     bool createCollection(const std::string& name, const CollectionOptions& options = {});
 
+    // v2.13.1 - the largest stored body a read can still send back (JSON
+    // text bytes); a patch whose result exceeds it is refused (TooLarge).
+    // 0 = no limit. Set by DatabaseService from the gRPC send limit.
+    void setMaxDocumentBytes(size_t bytes) { maxDocumentBytes_.store(bytes); }
+    size_t maxDocumentBytes() const { return maxDocumentBytes_.load(); }
+
     /**
      * Drop a collection and all its documents.
      * @return true if dropped, false if not found
@@ -627,7 +633,8 @@ public:
 
     // v2.12.0 - why patchDocument() below returned 0.
     struct PatchRefusal {
-        enum class Kind { None, NotFound, VersionConflict, InvalidIncrement };
+        enum class Kind { None, NotFound, VersionConflict, InvalidIncrement,
+                          TooLarge };   // v2.13.1 - the merged row could not be read back
         Kind kind = Kind::None;
         uint64_t currentVersion = 0;   // VersionConflict: the stored version
         std::string field;             // InvalidIncrement: the offending path
@@ -1418,6 +1425,10 @@ private:
     // unset, mirrorWriteToDocStore / mirrorVectorToDocStore are no-ops
     // (preserves test/bootstrap paths that don't wire LMDB).
     DocumentStoreResolver docStoreResolver_;
+
+    // v2.13.1 - the largest stored body (JSON text) a read can still send back;
+    // 0 = no limit. Set by DatabaseService from the gRPC send limit.
+    std::atomic<size_t> maxDocumentBytes_{0};
     // v2.11.0 close-out — see setTtlExpiryRelationHook(). Written once at boot
     // (before the expiration thread does anything that consults it) and read
     // from the cleanup thread only.

+ 31 - 0
tests/load_test/test_export.cpp

@@ -294,6 +294,37 @@ static void check() {
     ck(afterBig.summary.complete && afterBig.rows.size() == 1 && afterBig.rows[0].id == "b2",
        "resuming after the named row completes the rest");
 
+    // --- v2.13.1: a write that would leave an unreadable row is refused.
+    // The server now runs with a 2 MB send limit (so 1.75 MB per stored body).
+    auto codeAndReason = [](const std::function<void()>& fn) {
+        try { fn(); } catch (const Client::Error& e) {
+            auto* d = Client::errorDetail(e);
+            return std::make_pair(e.code(), d ? d->reason : std::string{});
+        }
+        return std::make_pair(Client::ErrorCode::Ok, std::string{});
+    };
+    const std::string mb19(1900 * 1024, 'z');
+    auto ins = codeAndReason([&] { c.insert("guard", {{"blob", mb19}}, "too-big"); });
+    ck(ins.first == Client::ErrorCode::InvalidArgument && ins.second == "document_too_large",
+       "guard: an insert no read could return is refused, document_too_large");
+    ck(!c.get("guard", "too-big"), "guard: the refused insert stored nothing");
+    auto ups = codeAndReason([&] { (void)c.upsert("guard", {{"blob", mb19}}, "too-big-up"); });
+    ck(ups.first == Client::ErrorCode::InvalidArgument && ups.second == "document_too_large",
+       "guard: an oversized upsert is refused");
+    c.insert("guard", {{"blob", std::string(1000 * 1024, 'a')}}, "g1");
+    Client::FailureDetail pd;
+    ck(c.patch("guard", "g1", {{"more", std::string(1000 * 1024, 'b')}}, pd) == 0 &&
+           pd.code == Client::ErrorCode::InvalidArgument && pd.reason == "document_too_large",
+       "guard: a patch that would GROW the row past the limit is refused (" + pd.reason + ")");
+    auto g1 = c.get("guard", "g1");
+    ck(g1 && !g1->contains("more") && (*g1)["_version"] == 1,
+       "guard: the refused patch left the row untouched and readable");
+    ck(c.patch("guard", "g1", {{"small", 1}}, pd) > 0, "guard: a patch that fits still works");
+    Client::FailureDetail ud;
+    ck(!c.update("guard", "g1", {{"blob", mb19}}, ud) && ud.code == Client::ErrorCode::InvalidArgument &&
+           ud.reason == "document_too_large",
+       "guard: an oversized update is refused");
+
     // --- file calls report a reason
     Client::Failure ff;
     ck(!c.setFileTtl("no-such-file", 60, ff) && ff.code == Client::ErrorCode::NotFound,

+ 14 - 2
tests/load_test/test_export.sh

@@ -15,6 +15,11 @@ PORT=9023
 rm -rf "$DIR"
 mkdir -p "$DIR/data"
 
+# Two configs over one data directory. The write phase runs with the default
+# 100 MB send limit, so it can store a 3 MB row; every later phase runs with a
+# 2 MB send limit, which makes that row unreadable - the state 2.13.1's write
+# guard otherwise prevents (a row from before it, or a limit lowered later).
+write_config() {
 cat > "$DIR/config.json" <<CFG
 {
   "storage": {
@@ -24,10 +29,12 @@ cat > "$DIR/config.json" <<CFG
     "encryption": { "enabled": false },
     "migrations": { "enabled": false },
     "replication": { "enabled": false },
-    "grpc": { "max_send_message_size_mb": 2 }
+    "grpc": { "max_send_message_size_mb": $1 }
   }
 }
 CFG
+}
+write_config 100
 
 echo "=== building test binary ==="
 g++ -std=c++20 -O1 -o "$DIR/t" test_export.cpp \
@@ -74,12 +81,17 @@ if grep -rqa mallory "$DIR/data"; then
 fi
 echo "PASS: no reserved-name value on disk"
 
+echo "=== restart with a 2 MB send limit ==="
+stop
+write_config 2
+start 2
+
 echo "=== check ==="
 run check
 
 echo "=== restart ==="
 stop
-start 2
+start 3
 echo "=== after restart ==="
 run after
 

+ 55 - 3
tests/load_test/test_read_failures.cpp

@@ -23,6 +23,7 @@
 // tryGetRelationsEnforced() declines, getRelationsEnforced() fails toward true.
 
 #include <smartbotic/database/client.hpp>
+#include <chrono>
 #include <functional>
 #include <iostream>
 #include <string>
@@ -68,7 +69,8 @@ static std::vector<std::pair<std::string, std::function<bool(Client&)>>> reads()
 
 static int absent() {
     Client c({.address = "127.0.0.1:9022", .project = "rf"});
-    c.connect();
+    ck(c.connect(), "absent: connect() reaches a running server");   // v2.13.1
+    ck(c.isConnected(), "absent: isConnected() after a real connection");
     // Something to be present, so the absences below are absences inside a
     // working collection and not just a server with nothing in it.
     c.insert("things", nlohmann::json{{"k", "v"}}, "t1");
@@ -97,8 +99,11 @@ static int absent() {
 static void failing(const char* phase, Client::ErrorCode want) {
     Client c({.address = "127.0.0.1:9022", .timeoutMs = 700, .maxRetries = 0,
               .writeRetries = 0, .project = "rf"});
-    c.connect();
     const std::string p = phase;
+    // v2.13.1 - connect() used to return true (and log "connected") without
+    // opening anything, so it said yes against a dead or frozen server.
+    ck(!c.connect(), p + ": connect() reports the server unreachable");
+    ck(!c.isConnected(), p + ": isConnected() is false after the failed attempt");
     for (auto& [name, read] : reads()) {
         bool typed = false;
         Client::ErrorCode got = Client::ErrorCode::Ok;
@@ -132,10 +137,57 @@ static void failing(const char* phase, Client::ErrorCode want) {
     ck(!threw && g, p + ": getRelationsEnforced fails toward true without throwing");
 }
 
+// v2.13.1 - a write that timed out may have been APPLIED (the deadline can
+// expire while the server finishes it), so only an idempotent write is retried
+// after DEADLINE_EXCEEDED, and every such failure says outcome_unknown. Timing
+// tells a retry from none: writeRetries=2 at 500 ms is >= 1.5 s when retried.
+static void writeTimeouts() {
+    Client w({.address = "127.0.0.1:9022", .timeoutMs = 500, .maxRetries = 0,
+              .writeRetries = 2, .writeRetryBackoffMs = 50, .project = "rf"});
+    (void)w.connect();   // frozen: false after 500 ms, the client stays usable
+    using clk = std::chrono::steady_clock;
+    auto ms = [](clk::time_point t) {
+        return std::chrono::duration_cast<std::chrono::milliseconds>(clk::now() - t).count();
+    };
+
+    auto t = clk::now();
+    std::string reason;
+    Client::ErrorCode code = Client::ErrorCode::Ok;
+    try { w.insert("things", nlohmann::json{{"k", 1}}); }
+    catch (const Client::Error& e) { code = e.code(); if (auto* d = Client::errorDetail(e)) reason = d->reason; }
+    auto el = ms(t);
+    ck(code == Client::ErrorCode::DeadlineExceeded && reason == "outcome_unknown",
+       "frozen: a timed-out insert says DeadlineExceeded / outcome_unknown ('" + reason + "')");
+    ck(el < 1200, "frozen: an insert is NOT retried after a timeout (" + std::to_string(el) + " ms)");
+
+    t = clk::now();
+    Client::FailureDetail pd;
+    (void)w.patch("things", "t1", nlohmann::json{{"k", 2}}, pd);
+    el = ms(t);
+    ck(pd.code == Client::ErrorCode::DeadlineExceeded && pd.reason == "outcome_unknown",
+       "frozen: a timed-out patch says outcome_unknown");
+    ck(el >= 1400, "frozen: a plain (idempotent) patch IS retried (" + std::to_string(el) + " ms)");
+
+    t = clk::now();
+    Client::FailureDetail id;
+    (void)w.increment("things", "t1", nlohmann::json{{"k", 1}}, id);
+    el = ms(t);
+    ck(id.code == Client::ErrorCode::DeadlineExceeded && id.reason == "outcome_unknown",
+       "frozen: a timed-out increment says outcome_unknown");
+    ck(el < 1200, "frozen: an increment is NOT retried, it would count twice (" + std::to_string(el) + " ms)");
+
+    t = clk::now();
+    Client::Failure rf;
+    (void)w.remove("things", "t1", rf);
+    el = ms(t);
+    ck(rf.code == Client::ErrorCode::DeadlineExceeded, "frozen: a timed-out remove says DeadlineExceeded");
+    ck(el < 1200, "frozen: a remove is NOT retried (" + std::to_string(el) + " ms)");
+}
+
 int main(int argc, char** argv) {
     const std::string phase = argc > 1 ? argv[1] : "";
     if (phase == "absent") absent();
-    else if (phase == "frozen") failing("frozen", Client::ErrorCode::DeadlineExceeded);
+    else if (phase == "frozen") { failing("frozen", Client::ErrorCode::DeadlineExceeded); writeTimeouts(); }
     else if (phase == "down") failing("down", Client::ErrorCode::Unavailable);
     else { std::cerr << "usage: absent|frozen|down\n"; return 2; }
     std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно