Просмотр исходного кода

feat: 2.13.0 - stored vectors read back, a collection export that is a real backup

Requested by smartbotic-vectorapi: nothing returned a stored embedding (the
server moves _vector into _vectors_<collection> on write), so an export of a
vector collection would re-import as unsearchable JSON. Design agreed with
them before any code.

Read-back: get/find overloads taking a Client::WithVector tag return
"_vector": [floats], the field insert takes. Wire: include_vector on
GetRequest/FindRequest, raw float32-le bytes in Document.vector.

ExportCollection (server stream) + Client::exportCollection(): one
collection, never a project (vectorapi's tenancy is a collection-name prefix),
gated as an ordinary read. One stream is one LMDB read transaction: an exact
snapshot in id order with its row count in the header. Resume via after_id
never repeats a row. Batches clamped (256 default, 1024 max, 8 MB), a 600 s
stream cap ends a stream with complete=false and a cursor, 8 concurrent
exports. The client throws on a stream without its trailer and on an unknown
dtype. Per-row VectorState: Present / None / Missing / Unknown, reported as
stored; a has-vector marker on the stored document tells None from Missing.

Defects fixed on the way:
- A document and its vector were two LMDB commits, so a snapshot between them
  saw the row without its vector. Now one transaction (put_with_vector).
- insert/upsert/update/patch STORED the six read-metadata names from a write
  body as hidden user fields. The server now strips them on every write path.
- deleteFile/setFileTtl could not tell "no such file" from a failed call; they
  get Failure& / FailureDetail& overloads.
- A throwing subscribeEvents handler terminated the consumer process; the
  event is now logged and dropped.

Restored rows get fresh metadata (agreed; no preserving write mode).

Tests: test_export_scan (30, store level, incl. Missing/Unknown and a
concurrent writer+exporter) and test_export e2e (port 9023, 85 checks + an
on-disk check: the full export -> insert round trip, resume, refusals, a
restart, a race, an outage). Each part reverted alone fails a test; the
two-commit write shows 16,592 false Missing rows at the store level (0 with
the fix). The e2e race phase cannot see that revert, because the export
handler's collection lookup serialises with writers; documented.

ABI: soname 2, no existing public type changed; additions only.
fszontagh 1 месяц назад
Родитель
Сommit
4e4bfcd75e

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.12.4
+2.13.0

+ 107 - 0
client/include/smartbotic/database/client.hpp

@@ -315,6 +315,24 @@ public:
      */
     [[nodiscard]] std::optional<nlohmann::json> get(const std::string& collection, const std::string& id);
 
+    /**
+     * v2.13.0 - tag selecting the read overloads that also return the stored
+     * vector: `db.get("docs", id, Client::WithVector{})`. A tag type rather
+     * than a bool parameter or a QueryOptions member, so nothing existing
+     * changes size or meaning.
+     */
+    struct WithVector {};
+
+    /**
+     * get(), plus the document's stored vector as "_vector": [floats] - the
+     * same field insert() takes, so a document read this way can be written
+     * straight back and stays searchable. No "_vector" key means no vector is
+     * stored. The other read paths never return it, because the server moves
+     * `_vector` out of the body on write.
+     */
+    [[nodiscard]] std::optional<nlohmann::json> get(const std::string& collection,
+                                                    const std::string& id, WithVector);
+
     /**
      * Replace a whole document. This OVERWRITES the existing doc — every
      * field not in `data` is dropped.
@@ -746,12 +764,89 @@ public:
                                                    const QueryOptions& options,
                                                    const std::vector<std::string>& projection);
 
+    /**
+     * v2.13.0 - find(), with each document's stored vector as "_vector" (see
+     * get(..., WithVector)). Not for a view: a view projects fields, and a
+     * vector is not one. For a whole collection use exportCollection(), which
+     * streams instead of building one response.
+     */
+    [[nodiscard]] std::vector<nlohmann::json> find(const std::string& collection,
+                                                   const QueryOptions& options, WithVector);
+
     /**
      * Find documents with full metrics (including WAL fallback info).
      */
     [[nodiscard]] FindResult findWithMetrics(const std::string& collection,
                                               const QueryOptions& options);
 
+    // ===== Export (v2.13.0) =====
+
+    /** What an exported row says about its vector. */
+    enum class VectorState : int {
+        Unspecified = 0,   ///< vectors were not requested
+        Present = 1,       ///< stored; ExportRow::vector holds it
+        None = 2,          ///< the row was written without a vector
+        Missing = 3,       ///< the row was written WITH a vector and its entry is gone
+        Unknown = 4,       ///< no entry, and the row predates the marker (written before 2.13.0)
+    };
+
+    struct ExportHeader {
+        std::string collection;
+        uint32_t vectorDimension = 0;
+        std::string vectorDtype;          ///< informational; the client converts ("float32-le")
+        uint64_t rowsAtSnapshot = 0;      ///< rows this stream sends if it completes
+        uint32_t batchRowsEffective = 0;  ///< batch_rows after the server clamped it
+        uint32_t maxStreamSeconds = 0;    ///< one stream ends (complete=false) after this
+    };
+
+    struct ExportRow {
+        std::string id;                   ///< the id to insert the row back under
+        nlohmann::json document;          ///< same shape as get(): fields + _id/_version/... metadata
+        VectorState vectorState = VectorState::Unspecified;
+        std::vector<float> vector;        ///< the stored vector when vectorState is Present
+    };
+
+    struct ExportSummary {
+        uint64_t rowsSent = 0;            ///< rows delivered to the handler
+        std::string lastId;               ///< resume cursor: pass as afterId to continue
+        bool complete = false;            ///< true only when the end of the collection was reached
+    };
+
+    /**
+     * v2.13.0 - stream one collection out: every document, and with
+     * `includeVectors` its stored vector and VectorState.
+     *
+     * - Scope is ONE collection, named as everywhere else (qualified by the
+     *   client's project). There is no project-wide export: a whole-tenant
+     *   export is the caller's loop over its own collections.
+     * - One call is one snapshot: rows arrive in id order, none skipped or
+     *   repeated, and rowsSent == header.rowsAtSnapshot when complete.
+     * - Resume with afterId = summary.lastId. A resume is a NEW snapshot after
+     *   that id: it never repeats a row, but can miss a row inserted during the
+     *   gap with an id sorting before the cursor.
+     * - complete=false means the export stopped early: the handler returned
+     *   false (that row counts as delivered and is lastId), or the server's
+     *   time cap (header.maxStreamSeconds) ended the stream. Resume from lastId.
+     * - Throws Client::Error on a failed call; on a stream that ends without
+     *   its trailer (it did not complete, whatever it delivered); on an
+     *   unrecognised vector dtype (Unimplemented, never reinterpreted); and
+     *   with InvalidArgument (reason "no_vector_index") when includeVectors is
+     *   asked of a collection with vector_dimension 0.
+     * - Restoring: insert(collection, row.document, row.id) on an empty
+     *   collection of the same vector_dimension gives the same fields, and with
+     *   row.document["_vector"] = row.vector the same searchable vector. The
+     *   restored row gets FRESH metadata (_created_at, _version, ...): the
+     *   server stamps those and accepts none from a caller. The originals stay
+     *   in row.document; copy them into a field of your own before importing if
+     *   you need them as data.
+     * - `batchRows` 0 = the server default (256); larger values are clamped.
+     */
+    ExportSummary exportCollection(const std::string& collection, bool includeVectors,
+                                   const std::string& afterId,
+                                   const std::function<void(const ExportHeader&)>& onHeader,
+                                   const std::function<bool(ExportRow&&)>& onRow,
+                                   uint32_t batchRows = 0);
+
     /**
      * Count documents matching filters.
      */
@@ -1647,6 +1742,18 @@ public:
      */
     bool setFileTtl(const std::string& id, uint32_t ttlSeconds);
 
+    /**
+     * v2.13.0 - deleteFile/setFileTtl with a reason. The bool forms answer
+     * false both for "no such file" and for a call that failed, so an outage
+     * read as an absent file. These record NotFound when the server answered
+     * that the file is not there (or, for setFileTtl, already expired), and the
+     * real code (Unavailable, DeadlineExceeded, ...) when the call failed.
+     */
+    bool deleteFile(const std::string& id, Failure& failureOut);
+    bool deleteFile(const std::string& id, FailureDetail& failureOut);
+    bool setFileTtl(const std::string& id, uint32_t ttlSeconds, Failure& failureOut);
+    bool setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureDetail& failureOut);
+
     [[nodiscard]] FileListResult listFiles(const std::string& file_type = "",
                                             const std::string& related_id = "",
                                             uint32_t limit = 100, uint32_t offset = 0,

+ 218 - 21
client/src/client.cpp

@@ -11,6 +11,7 @@
 #include <atomic>
 #include <chrono>
 #include <cstdlib>
+#include <cstring>
 #include <fstream>
 #include <mutex>
 #include <sstream>
@@ -180,6 +181,30 @@ struct FailureSink {
     }
 };
 
+// The JSON a read hands back: the stored fields plus the read metadata, and
+// (v2.13.0) "_vector" when the server sent the stored vector, which it does
+// only when the caller asked. The bytes are float32 little-endian.
+nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) {
+    auto json = nlohmann::json::parse(doc.data());
+    json["_id"] = doc.id();
+    json["_version"] = doc.version();
+    json["_created_at"] = doc.created_at();
+    json["_updated_at"] = doc.updated_at();
+    json["_created_by"] = doc.created_by();
+    json["_updated_by"] = doc.updated_by();
+    if (!doc.vector().empty()) {
+        if (doc.vector().size() % sizeof(float) != 0) {
+            throw DetailedError(Client::ErrorCode::DataLoss,
+                                "stored vector is not a whole number of float32 values",
+                                makeDetail(Client::ErrorCode::DataLoss, "bad vector bytes", {}));
+        }
+        std::vector<float> v(doc.vector().size() / sizeof(float));
+        std::memcpy(v.data(), doc.vector().data(), doc.vector().size());
+        json["_vector"] = v;
+    }
+    return json;
+}
+
 // v1.7.0 T11 — transient transport errors that are safe to retry for idempotent
 // writes (insert with explicit ID, updateIfVersion, upsert, remove, patch).
 // All other codes (INVALID_ARGUMENT, FAILED_PRECONDITION, NOT_FOUND, ...) are
@@ -438,10 +463,12 @@ public:
         return response.id();
     }
 
-    std::optional<nlohmann::json> get(const std::string& collection, const std::string& id) {
+    std::optional<nlohmann::json> get(const std::string& collection, const std::string& id,
+                                      bool includeVector = false) {
         smartbotic::databasepb::GetRequest request;
         request.set_collection(qualify(collection));
         request.set_id(id);
+        request.set_include_vector(includeVector);   // v2.13.0
 
         smartbotic::databasepb::GetResponse response;
         grpc::ClientContext context;
@@ -465,15 +492,7 @@ public:
         if (!response.found()) {
             return std::nullopt;
         }
-
-        auto json = nlohmann::json::parse(response.document().data());
-        json["_id"] = response.document().id();
-        json["_version"] = response.document().version();
-        json["_created_at"] = response.document().created_at();
-        json["_updated_at"] = response.document().updated_at();
-        json["_created_by"] = response.document().created_by();
-        json["_updated_by"] = response.document().updated_by();
-        return json;
+        return documentToJson(response.document());
     }
 
     bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
@@ -839,7 +858,8 @@ public:
 
     std::vector<nlohmann::json> find(const std::string& collection,
                                      const Client::QueryOptions& options,
-                                     const std::vector<std::string>& projection = {}) {
+                                     const std::vector<std::string>& projection = {},
+                                     bool includeVector = false) {
         smartbotic::databasepb::FindRequest request;
         request.set_collection(qualify(collection));
 
@@ -868,6 +888,7 @@ public:
         for (const auto& f : projection) {
             request.add_projection(f);
         }
+        request.set_include_vector(includeVector);   // v2.13.0
 
         smartbotic::databasepb::FindResponse response;
         grpc::ClientContext context;
@@ -898,14 +919,7 @@ public:
         std::vector<nlohmann::json> results;
         results.reserve(response.documents_size());
         for (const auto& doc : response.documents()) {
-            auto json = nlohmann::json::parse(doc.data());
-            json["_id"] = doc.id();
-            json["_version"] = doc.version();
-            json["_created_at"] = doc.created_at();
-            json["_updated_at"] = doc.updated_at();
-            json["_created_by"] = doc.created_by();
-            json["_updated_by"] = doc.updated_by();
-            results.push_back(json);
+            results.push_back(documentToJson(doc));
         }
 
         return results;
@@ -2122,6 +2136,11 @@ public:
         auto readerThread = std::thread([reader = reader.get(), handler = std::move(handler)]() {
             smartbotic::databasepb::DatabaseEvent event;
             while (reader->Read(&event)) {
+              // v2.13.0 - nothing may escape this thread: an exception leaving a
+              // std::thread calls std::terminate, so one throwing handler (or one
+              // event body that does not parse) used to take the whole consumer
+              // process down. The event is logged and dropped; the stream goes on.
+              try {
                 std::optional<nlohmann::json> data;
                 if (!event.data().empty()) {
                     data = nlohmann::json::parse(event.data());
@@ -2147,6 +2166,15 @@ public:
                 out.timestamp = event.timestamp();
                 out.nodeId = event.node_id();
                 handler(out);
+              } catch (const std::exception& e) {
+                spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler "
+                              "or its parse threw: {}", event.collection(),
+                              event.document_id(), e.what());
+              } catch (...) {
+                spdlog::error("Client::subscribeEvents: event {}/{} dropped, the handler "
+                              "threw a non-std exception", event.collection(),
+                              event.document_id());
+              }
             }
         });
 
@@ -2157,6 +2185,126 @@ public:
         );
     }
 
+    // ===== Export (v2.13.0) =====
+    //
+    // The server's contract is in the proto, above ExportRequest. What this
+    // side adds: a stream that ends without its trailer THROWS (it is not a
+    // complete export, whatever it delivered); an unrecognised vector dtype
+    // THROWS rather than being reinterpreted; and a handler returning false
+    // stops the export AFTER that row, which therefore counts as delivered
+    // (lastId names it, so a resume starts after it).
+
+    Client::ExportSummary exportCollection(
+            const std::string& collection, bool includeVectors, const std::string& afterId,
+            const std::function<void(const Client::ExportHeader&)>& onHeader,
+            const std::function<bool(Client::ExportRow&&)>& onRow,
+            uint32_t batchRows) {
+        smartbotic::databasepb::ExportRequest request;
+        request.set_collection(qualify(collection));
+        request.set_include_vectors(includeVectors);
+        request.set_after_id(afterId);
+        request.set_batch_rows(batchRows);
+
+        // Not the per-call timeout: an export is long by design. The server
+        // ends a stream at its own cap (header.max_stream_seconds, 600) with a
+        // resume cursor; this deadline is only the backstop for a server that
+        // stops answering.
+        grpc::ClientContext context;
+        context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(900));
+        attachAuth(context);
+        auto reader = stub_->ExportCollection(&context, request);
+
+        auto abandon = [&]() {
+            context.TryCancel();
+            smartbotic::databasepb::ExportChunk drain;
+            while (reader->Read(&drain)) {}
+            (void)reader->Finish();
+        };
+
+        Client::ExportSummary summary;
+        bool sawHeader = false;
+        bool sawTrailer = false;
+        smartbotic::databasepb::ExportTrailer trailer;
+        smartbotic::databasepb::ExportChunk chunk;
+        while (reader->Read(&chunk)) {
+            if (chunk.has_header()) {
+                const auto& h = chunk.header();
+                if (h.vector_dtype() != "float32-le") {
+                    abandon();
+                    const std::string msg = "export: unrecognised vector dtype '" +
+                                            h.vector_dtype() + "'; refusing to reinterpret the bytes";
+                    throw DetailedError(Client::ErrorCode::Unimplemented, msg,
+                                        makeDetail(Client::ErrorCode::Unimplemented, msg, {}));
+                }
+                sawHeader = true;
+                Client::ExportHeader out;
+                out.collection = unqualify(h.collection());
+                out.vectorDimension = h.vector_dimension();
+                out.vectorDtype = h.vector_dtype();
+                out.rowsAtSnapshot = h.rows_at_snapshot();
+                out.batchRowsEffective = h.batch_rows_effective();
+                out.maxStreamSeconds = h.max_stream_seconds();
+                if (onHeader) {
+                    try { onHeader(out); } catch (...) { abandon(); throw; }
+                }
+            } else if (chunk.has_rows()) {
+                for (auto& r : *chunk.mutable_rows()->mutable_rows()) {
+                    Client::ExportRow row;
+                    row.id = r.document().id();
+                    row.vectorState = static_cast<Client::VectorState>(r.vector_state());
+                    const std::string& bytes = r.document().vector();
+                    if (!bytes.empty()) {
+                        if (bytes.size() % sizeof(float) != 0) {
+                            abandon();
+                            const std::string msg = "export: vector of '" + row.id +
+                                                    "' is not a whole number of float32 values";
+                            throw DetailedError(Client::ErrorCode::DataLoss, msg,
+                                                makeDetail(Client::ErrorCode::DataLoss, msg, {}));
+                        }
+                        row.vector.resize(bytes.size() / sizeof(float));
+                        std::memcpy(row.vector.data(), bytes.data(), bytes.size());
+                        r.mutable_document()->clear_vector();   // the vector is row.vector, not "_vector"
+                    }
+                    row.document = documentToJson(r.document());
+                    std::string id = row.id;
+                    bool more = true;
+                    try { more = onRow(std::move(row)); } catch (...) { abandon(); throw; }
+                    ++summary.rowsSent;
+                    summary.lastId = std::move(id);
+                    if (!more) {
+                        abandon();
+                        summary.complete = false;
+                        return summary;
+                    }
+                }
+            } else if (chunk.has_trailer()) {
+                sawTrailer = true;
+                trailer = chunk.trailer();
+            }
+        }
+        auto status = reader->Finish();
+        if (!status.ok()) {
+            spdlog::error("Client::exportCollection failed: {}", status.error_message());
+            throwStatus(status, status.error_message(), trailerDetail(context));
+        }
+        if (!sawHeader || !sawTrailer) {
+            const std::string msg = "export of '" + collection + "' ended without its trailer "
+                                    "after " + std::to_string(summary.rowsSent) +
+                                    " rows; it did not complete";
+            throw DetailedError(Client::ErrorCode::Unavailable, msg,
+                                makeDetail(Client::ErrorCode::Unavailable, msg, {}));
+        }
+        if (trailer.rows_sent() != summary.rowsSent) {
+            const std::string msg = "export of '" + collection + "': server reports " +
+                                    std::to_string(trailer.rows_sent()) + " rows sent, " +
+                                    std::to_string(summary.rowsSent) + " arrived";
+            throw DetailedError(Client::ErrorCode::DataLoss, msg,
+                                makeDetail(Client::ErrorCode::DataLoss, msg, {}));
+        }
+        summary.complete = trailer.complete();
+        return summary;
+    }
+
     // ===== Version History =====
 
     Client::VersionHistoryResult getVersionHistory(const std::string& collection,
@@ -2564,7 +2712,11 @@ public:
         return record;
     }
 
-    bool deleteFile(const std::string& id) {
+    // v2.13.0 - `failureOut` tells "no such file" (NotFound, answered in-band
+    // by the server) from a call that failed (the real code). The bool-only
+    // public form passes no sink and behaves exactly as before.
+    bool deleteFile(const std::string& id, FailureSink failureOut = {}) {
+        failureOut.reset();
         smartbotic::databasepb::DeleteFileRequest request;
         request.set_id(id);
         request.set_project(config_.project);
@@ -2576,12 +2728,18 @@ public:
         auto status = stub_->DeleteFile(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::deleteFile failed: {}", status.error_message());
+            failureOut.record(status);
             return false;
         }
+        if (!response.deleted()) {
+            failureOut.record(Client::ErrorCode::NotFound, "no such file in this project");
+        }
         return response.deleted();
     }
 
-    bool setFileTtl(const std::string& id, uint32_t ttlSeconds) {
+    // v2.13.0 - same contract as deleteFile above.
+    bool setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureSink failureOut = {}) {
+        failureOut.reset();
         smartbotic::databasepb::SetFileTtlRequest request;
         request.set_id(id);
         request.set_project(config_.project);
@@ -2594,8 +2752,13 @@ public:
         auto status = stub_->SetFileTtl(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::setFileTtl failed: {}", status.error_message());
+            failureOut.record(status);
             return false;
         }
+        if (!response.updated()) {
+            failureOut.record(Client::ErrorCode::NotFound,
+                              "no such file in this project, or it has already expired");
+        }
         return response.updated();
     }
 
@@ -2872,6 +3035,24 @@ std::vector<nlohmann::json> Client::find(const std::string& collection,
     return impl_->find(collection, options, projection);
 }
 
+std::vector<nlohmann::json> Client::find(const std::string& collection,
+                                         const QueryOptions& options, WithVector) {
+    return impl_->find(collection, options, {}, /*includeVector=*/true);
+}
+
+std::optional<nlohmann::json> Client::get(const std::string& collection,
+                                          const std::string& id, WithVector) {
+    return impl_->get(collection, id, /*includeVector=*/true);
+}
+
+Client::ExportSummary Client::exportCollection(
+        const std::string& collection, bool includeVectors, const std::string& afterId,
+        const std::function<void(const ExportHeader&)>& onHeader,
+        const std::function<bool(ExportRow&&)>& onRow, uint32_t batchRows) {
+    return impl_->exportCollection(collection, includeVectors, afterId, onHeader, onRow,
+                                   batchRows);
+}
+
 Client::FindResult Client::findWithMetrics(const std::string& collection,
                                             const QueryOptions& options) {
     return impl_->findWithMetrics(collection, options);
@@ -3139,6 +3320,22 @@ bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds) {
     return impl_->setFileTtl(id, ttlSeconds);
 }
 
+bool Client::deleteFile(const std::string& id, Failure& failureOut) {
+    return impl_->deleteFile(id, &failureOut);
+}
+
+bool Client::deleteFile(const std::string& id, FailureDetail& failureOut) {
+    return impl_->deleteFile(id, &failureOut);
+}
+
+bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, Failure& failureOut) {
+    return impl_->setFileTtl(id, ttlSeconds, &failureOut);
+}
+
+bool Client::setFileTtl(const std::string& id, uint32_t ttlSeconds, FailureDetail& failureOut) {
+    return impl_->setFileTtl(id, ttlSeconds, &failureOut);
+}
+
 Client::FileListResult Client::listFiles(const std::string& file_type,
                                           const std::string& related_id,
                                           uint32_t limit, uint32_t offset,

+ 8 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.12.4** (see `VERSION`). Last reviewed: 2026-10-07.
+**Released version: 2.13.0** (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.12.4. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.13.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -91,6 +91,12 @@ detail and the failure modes.
   empty/nullopt/false/0, on every read whose empty value is also a valid
   answer; `update()` reports an outage with its real code, not `NotFound`
   (2.12.4)
+- Stored vectors read back (`get`/`find` with `Client::WithVector`) and a
+  streaming per-collection export (`ExportCollection`, `exportCollection()`)
+  with an exact-snapshot cursor, a resume cursor and a per-row `VectorState`;
+  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)
 - Conditional partial update (`patchIfVersion`) and atomic increment
   (`increment`) (2.12.0)
 - Event provenance: the actor on every `DatabaseEvent`, `removeAs()`,

+ 109 - 0
docs/integration-guide.md

@@ -327,6 +327,35 @@ background thread, where an uncaught exception terminates the process - must
 catch `Client::Error` (or `std::exception`). The soname is unchanged, so this
 applies as soon as the library is upgraded, without a rebuild.
 
+**Where the catch actually has to be** - found by a consumer auditing for this
+release, each one a real bug it already had:
+
+- **The adapter, not the call site.** A wrapper that turns client calls into a
+  `Result` must catch `Client::Error` itself, or every caller behind it inherits
+  the throw. And it must not catch too *broadly*: a wrapper that caught
+  `std::exception` and answered "collection not found" for all of them turned an
+  outage into a definite 404 one layer up - the exact bug this release fixes.
+  Treat only `code() == NotFound` (or a nullopt / empty answer) as absence.
+- **A read used as a yes/no test.** `if (!db.getCollectionInfo(name))` or
+  `.ok()` inside a loop deciding "does this exist / is this mine" drops a row on
+  a single timeout, even when the outer function is guarded. Only a definite
+  answer may mean "no".
+- **Worker threads.** An exception leaving a `std::thread` calls
+  `std::terminate`. A retention sweep or scheduler that calls the client with no
+  handler anywhere on its thread takes the whole process down on one blip.
+- **The file calls have always thrown** (`uploadFile`, `downloadFile`,
+  `getFileInfo`, `listFiles`), so an audit prompted by 2.12.4 can miss them.
+- **`getCollectionConfig()` before 2.12.4 answered the DEFAULTS on failure** - an
+  outage read as "versioning disabled" on a collection that has it on. It throws
+  now; code that compared its answer against defaults should be re-checked.
+- **`deleteFile()` / `setFileTtl()`** answer a bare `false` for "no such file" and
+  for a failed call alike. Since 2.13.0 their `Failure&` overloads say which:
+  `NotFound` when the file is not there, the real code when the call failed.
+- **Event handlers.** Before 2.13.0 a `subscribeEvents()` handler that threw (or
+  an event body that did not parse) terminated the process from the reader
+  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.
+
 #### The full reason: `FailureDetail` (2.12.0+)
 
 A status code alone is ambiguous - `FailedPrecondition` means a missing parent,
@@ -507,6 +536,86 @@ Relations are enforced exactly as for `removeAs()`, and all-or-nothing on
 `restrict`: if any id is protected, nothing is deleted (reason
 `delete_restricted`). Every delete carries the actor onto its event.
 
+### Reading vectors back, and exporting a collection (2.13.0+)
+
+`_vector` is moved out of a document on write (into the vector index), so an
+ordinary `get`/`find` never returns it. Ask for it explicitly:
+
+```cpp
+auto doc  = db.get("chunks", id, Client::WithVector{});      // doc->at("_vector") if one is stored
+auto docs = db.find("chunks", {.filters = {...}}, Client::WithVector{});
+```
+
+The vector comes back as `"_vector": [floats]` - the field `insert()` takes - so a
+document read this way can be written straight back and stays searchable. No
+`"_vector"` key means no vector is stored. Not available on a view.
+
+**Exporting a whole collection** streams it instead of building one response:
+
+```cpp
+auto sum = db.exportCollection("chunks", /*includeVectors=*/true, /*afterId=*/"",
+    [&](const Client::ExportHeader& h) { /* h.vectorDimension, h.rowsAtSnapshot */ },
+    [&](Client::ExportRow&& row) {
+        // row.id, row.document (same shape as get()), row.vectorState, row.vector
+        archive.write(row);
+        return true;                       // false = stop after this row
+    });
+if (!sum.complete) { /* resume: exportCollection(..., sum.lastId, ...) */ }
+```
+
+- **One collection, never a project.** The collection is named as everywhere
+  else; a whole-tenant export is your loop over your own collections. Gated as
+  an ordinary read of that collection (masks and row predicates apply).
+- **One call is one snapshot**: rows in id order, none skipped or repeated, and
+  `rowsSent == header.rowsAtSnapshot` when `complete`.
+- **Resuming** with `afterId = lastId` is a new snapshot strictly after that id
+  (an id that no longer exists works too: it resumes at the next id after it).
+  It never repeats a row, but can miss one inserted during the gap whose id sorts
+  before the cursor.
+- **`complete == false`** means the export stopped early: your handler returned
+  false (that row counts as delivered and is `lastId`), or the server's time cap
+  (`header.maxStreamSeconds`, 600 s) ended the stream. Resume from `lastId`.
+- **It throws** on a failed call, on a stream that ends without its trailer (it
+  did not complete, whatever it delivered), on an unrecognised vector dtype
+  (never reinterpreted), and with `InvalidArgument` / reason `no_vector_index`
+  when vectors are asked of a collection with `vector_dimension` 0.
+- `batchRows` (default 256) is clamped to 1024, never refused; batches are also
+  cut at 8 MB. The clamp is in `header.batchRowsEffective`.
+
+**`vectorState`**, reported as stored and never guessed by the library:
+
+| State | Meaning |
+|-------|---------|
+| `Present` | the vector is stored; `row.vector` holds it |
+| `None` | the row was written without a vector (or an `update()` without `_vector` removed it) |
+| `Missing` | the row was written WITH a vector and its entry is gone - real data loss; never write it back as a plain document |
+| `Unknown` | no entry, and the row was written before 2.13.0, which recorded no marker |
+| `Unspecified` | vectors were not requested |
+
+Since 2.13.0 a document and its vector are written in ONE transaction, so no
+reader (an export included) sees a row between the two; before, a snapshot
+could, and would have reported such a row as `Missing`.
+
+**Restoring** is `insert(collection, row.document, row.id)` with
+`row.document["_vector"] = row.vector` when `Present`, into a collection of the
+same `vector_dimension`. The restored row has the same fields and a
+byte-identical, searchable vector - but **fresh metadata**: `_created_at`,
+`_updated_at`, `_version` and `_created_by` are stamped by the server, which
+accepts none of them from a caller. The originals stay in `row.document` in your
+archive; copy them into a field of your own before importing if you need them as
+data.
+
+### Reserved names in a write body (2.13.0+)
+
+`_id`, `_version`, `_created_at`, `_updated_at`, `_created_by` and `_updated_by`
+are attached by every read and are never stored as fields. Since 2.13.0 the
+server strips them from every write body (insert, upsert, update, patch, batch
+insert), so a document read and written back - which is what a restore does -
+cannot store them. Before 2.13.0 insert/upsert/update stored them as ordinary
+fields that every read then hid: invisible, unfilterable (a filter on `_version`
+means the metadata), and carried into exports. Exports omit any such copies older
+rows still hold.
+
 ### Views
 
 Views are named, read-only projections over collections. They filter which fields are returned and optionally enforce baked-in filters and default sort order. Views are ideal for:

+ 83 - 0
proto/database.proto

@@ -69,6 +69,10 @@ service DatabaseService {
     rpc Count(CountRequest) returns (CountResponse);
     rpc SimilaritySearch(SimilaritySearchRequest) returns (SimilaritySearchResponse);
 
+    // v2.13.0 - stream one collection out, documents plus (optionally) their
+    // stored vectors. See ExportRequest for the contract.
+    rpc ExportCollection(ExportRequest) returns (stream ExportChunk);
+
     // Set operations (Redis compatibility)
     rpc SetAdd(SetAddRequest) returns (SetAddResponse);
     rpc SetRemove(SetRemoveRequest) returns (SetRemoveResponse);
@@ -189,6 +193,10 @@ message Document {
     repeated string encrypted_fields = 10;
     string created_by = 11;       // User ID who created the document
     string updated_by = 12;       // User ID who last updated the document
+    // v2.13.0 - the stored vector as raw float32 little-endian bytes. Set ONLY
+    // when the request asked for vectors (GetRequest/FindRequest
+    // include_vector, ExportRequest include_vectors) and a vector is stored.
+    bytes vector = 13;
 }
 
 // ===== Document Operations =====
@@ -209,6 +217,7 @@ message InsertResponse {
 message GetRequest {
     string collection = 1;
     string id = 2;
+    bool include_vector = 3;      // v2.13.0 - fill Document.vector
 }
 
 message GetResponse {
@@ -448,6 +457,7 @@ message FindRequest {
     uint32 limit = 4;             // Default 100
     uint32 offset = 5;
     repeated string projection = 6;  // Fields to include (empty = all)
+    bool include_vector = 7;      // v2.13.0 - fill Document.vector on each result
 }
 
 message Filter {
@@ -498,6 +508,79 @@ message CountResponse {
     uint64 count = 1;
 }
 
+// ===== Export (v2.13.0) =====
+//
+// One collection, never a project: the unit is a collection named exactly as
+// every other call names one, so a caller whose tenancy is a collection-name
+// prefix cannot be handed another tenant's rows. Gated as an ordinary READ of
+// that collection (column masks and row predicates apply), not admin.
+//
+// The stream is: one header, then row batches, then one trailer.
+//   - One stream is one LMDB read transaction: an exact snapshot, rows in id
+//     order, none skipped or repeated. header.rows_at_snapshot counts the rows
+//     the stream will send if it completes, so rows_sent == rows_at_snapshot
+//     checks it.
+//   - Resuming with after_id = trailer.last_id starts a NEW snapshot strictly
+//     after that id: it never repeats a row, but can miss one inserted during
+//     the gap with an id that sorts before the cursor.
+//   - A stream ends early (complete=false, last_id set) when it reaches the
+//     server's time cap (header.max_stream_seconds) - that is the resume case.
+//   - A stream that ends without a trailer did not complete. Treat it as
+//     failed; a client must never read a stream without a trailer as whole.
+//   - A restored row gets FRESH metadata: insert stamps _created_at,
+//     _updated_at, _version and _created_by itself. The originals are in each
+//     exported Document; keep them there, or copy them into your own field
+//     before importing if you need them as data.
+message ExportRequest {
+    string collection = 1;
+    // Include each row's vector (Document.vector) and its vector_state.
+    // Refused with INVALID_ARGUMENT (reason no_vector_index) on a collection
+    // with vector_dimension 0, which cannot hold vectors.
+    bool include_vectors = 2;
+    string after_id = 3;          // resume cursor; empty = from the start
+    uint32 batch_rows = 4;        // rows per ExportRows; 0 = default; clamped, never refused
+}
+
+enum VectorState {
+    VECTOR_STATE_UNSPECIFIED = 0; // include_vectors was false
+    VECTOR_STATE_PRESENT = 1;     // vector stored; Document.vector holds it
+    VECTOR_STATE_NONE = 2;        // written without a vector
+    VECTOR_STATE_MISSING = 3;     // written WITH a vector, and its entry is gone
+    VECTOR_STATE_UNKNOWN = 4;     // no entry, and the row predates the marker (pre-2.13.0)
+}
+
+message ExportHeader {
+    string collection = 1;
+    uint32 vector_dimension = 2;
+    string vector_dtype = 3;      // "float32-le"
+    uint64 rows_at_snapshot = 4;
+    uint32 batch_rows_effective = 5;
+    uint32 max_stream_seconds = 6;
+}
+
+message ExportRow {
+    Document document = 1;        // same shape as a Get result
+    VectorState vector_state = 2;
+}
+
+message ExportRows {
+    repeated ExportRow rows = 1;
+}
+
+message ExportTrailer {
+    uint64 rows_sent = 1;
+    string last_id = 2;           // id of the last row sent; the resume cursor
+    bool complete = 3;            // true only when the end of the collection was reached
+}
+
+message ExportChunk {
+    oneof chunk {
+        ExportHeader header = 1;
+        ExportRows rows = 2;
+        ExportTrailer trailer = 3;
+    }
+}
+
 message SimilaritySearchRequest {
     string collection = 1;
     repeated float query_vector = 2;

+ 208 - 0
service/src/database_grpc_impl.cpp

@@ -421,6 +421,7 @@ grpc::Status DatabaseGrpcImpl::Insert(
     }
     try {
         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;
 
         // v2.8.0 — a write to `_policies` is policy management, not a document
@@ -591,6 +592,10 @@ grpc::Status DatabaseGrpcImpl::Get(
         protoDoc.set_collection(request->collection());
     }
 
+    if (request->include_vector() && !view) {
+        attachStoredVector(protoDoc, targetCollection);   // v2.13.0
+    }
+
     *response->mutable_document() = std::move(protoDoc);
     response->set_found(true);
 
@@ -625,6 +630,7 @@ grpc::Status DatabaseGrpcImpl::Update(
     }
     try {
         nlohmann::json data = smartbotic::db::parse_to_nlohmann(request->data());
+        stripReservedFields(data);  // v2.13.0 - never store read metadata
 
         Document doc;
         doc.set_data(data);
@@ -731,6 +737,7 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
         nlohmann::json patch = request->patch_json().empty()
             ? nlohmann::json::object()
             : smartbotic::db::parse_to_nlohmann(request->patch_json());
+        stripReservedFields(patch);  // v2.13.0 - never store read metadata
 
         std::optional<nlohmann::json> increments;
         if (!request->increments_json().empty()) {
@@ -830,6 +837,7 @@ grpc::Status DatabaseGrpcImpl::Upsert(
     }
     try {
         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;
 
         // v2.8.0 — Upsert is a write path too. Policy management must be
@@ -1291,6 +1299,7 @@ grpc::Status DatabaseGrpcImpl::BatchInsert(
     for (const auto& item : request->items()) {
         try {
             nlohmann::json data = smartbotic::db::parse_to_nlohmann(item.data());
+            stripReservedFields(data);  // v2.13.0 - never store read metadata
 
             Document doc;
             doc.id = item.id();
@@ -1557,6 +1566,8 @@ grpc::Status DatabaseGrpcImpl::Find(
                 smartbotic::db::doc_binary::encode(docJson)));
             // Preserve view name as the observed collection
             protoDoc.set_collection(request->collection());
+        } else if (request->include_vector()) {
+            attachStoredVector(protoDoc, targetCollection);   // v2.13.0
         }
         *response->add_documents() = std::move(protoDoc);
     }
@@ -1826,6 +1837,187 @@ grpc::Status DatabaseGrpcImpl::SimilaritySearch(
     }
 }
 
+// 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;
+//   - one LMDB read transaction per stream (an exact snapshot), so the stream
+//     needs the LMDB substrate and refuses when the mirror is degraded rather
+//     than silently serving a MemoryStore cache that may have evicted rows;
+//   - batches are bounded by rows AND bytes, so no batch_rows can build a
+//     message past the gRPC limit;
+//   - the time cap ends the stream with complete=false and a resume cursor,
+//     because an open read transaction pins pages and grows the data file.
+namespace {
+constexpr uint32_t kExportDefaultBatchRows = 256;
+constexpr uint32_t kExportMaxBatchRows = 1024;
+constexpr size_t kExportMaxBatchBytes = 8u * 1024 * 1024;
+constexpr uint32_t kExportMaxStreamSeconds = 600;
+}  // namespace
+
+grpc::Status DatabaseGrpcImpl::ExportCollection(
+    grpc::ServerContext* context,
+    const pb::ExportRequest* request,
+    grpc::ServerWriter<pb::ExportChunk>* writer
+) {
+    const std::string& collection = request->collection();
+    if (collection.empty() || collection[0] == '_') {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                            "export needs a user collection name");
+    }
+    if (view_manager_.isView(collection)) {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                            "'" + collection + "' is a view; export the collection it projects");
+    }
+    auto info = store_.getCollectionInfo(collection);
+    if (!info) {
+        return grpc::Status(grpc::StatusCode::NOT_FOUND,
+                            "no collection named '" + collection + "'");
+    }
+    smartbotic::database::Decision dec;
+    if (auto st = gate(context, collection, smartbotic::database::Access::Read, dec); !st.ok()) {
+        return st;
+    }
+    const uint32_t dimension = info->options.vectorDimension;
+    if (request->include_vectors() && dimension == 0) {
+        attachErrorDetail(context, {{"reason", "no_vector_index"}});
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                            "'" + collection + "' has no vector index (vector_dimension 0), "
+                            "so it cannot hold vectors to export");
+    }
+    if (!service_.mirrorHealthy() || service_.mirrorDriftCount() != 0) {
+        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                            "export reads the LMDB store, which is degraded in this process "
+                            "(mirror unhealthy); restart the service to recover it");
+    }
+    StreamGuard guard(activeExportStreams_, maxExportStreams_, "ExportCollection");
+    if (!guard.ok()) {
+        return grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
+            "too many concurrent exports (max " + std::to_string(maxExportStreams_) + ")");
+    }
+
+    const uint32_t batchRows = request->batch_rows() == 0
+        ? kExportDefaultBatchRows
+        : std::min(request->batch_rows(), kExportMaxBatchRows);
+    const bool withVectors = request->include_vectors();
+    const auto deadline = std::chrono::steady_clock::now() +
+                          std::chrono::seconds(kExportMaxStreamSeconds);
+
+    // A policy row predicate decides visibility on the DECRYPTED document,
+    // exactly as Get/Find evaluate it.
+    std::function<bool(const Document&)> include;
+    if (!dec.row.empty()) {
+        include = [this, &dec](const Document& d) {
+            Document copy = d;
+            encryption_.decryptSensitiveFields(copy);
+            return store_.matchesFilters(copy, dec.row);
+        };
+    }
+
+    pb::ExportChunk batch;
+    size_t batchBytes = 0;
+    uint64_t rowsSent = 0;
+    std::string lastId;
+    bool stoppedEarly = false;
+    bool writeFailed = false;
+
+    auto flush = [&]() -> bool {
+        if (batch.rows().rows_size() == 0) return true;
+        const int n = batch.rows().rows_size();
+        if (!writer->Write(batch)) return false;
+        rowsSent += static_cast<uint64_t>(n);
+        lastId = batch.rows().rows(n - 1).document().id();
+        batch.Clear();
+        batchBytes = 0;
+        return true;
+    };
+
+    try {
+        const auto rc = smartbotic::database::resolveCollection(collection);
+        auto* ds = service_.docStore(rc.project);
+        if (!ds) {
+            return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                                "no document store for project '" + rc.project + "'");
+        }
+        using VS = smartbotic::db::storage::DocumentStore::ExportVectorState;
+        const bool found = ds->export_scan(
+            rc.collection, request->after_id(), withVectors, include,
+            [&](uint64_t rows) {
+                pb::ExportChunk head;
+                auto* h = head.mutable_header();
+                h->set_collection(collection);
+                h->set_vector_dimension(dimension);
+                h->set_vector_dtype("float32-le");
+                h->set_rows_at_snapshot(rows);
+                h->set_batch_rows_effective(batchRows);
+                h->set_max_stream_seconds(kExportMaxStreamSeconds);
+                if (!writer->Write(head)) writeFailed = true;
+            },
+            [&](Document&& doc, VS state, const float* vec, size_t n) -> bool {
+                if (writeFailed || context->IsCancelled() || shuttingDown_.load()) {
+                    stoppedEarly = true;
+                    return false;
+                }
+                if (std::chrono::steady_clock::now() >= deadline) {
+                    stoppedEarly = true;
+                    return false;
+                }
+                encryption_.decryptSensitiveFields(doc);
+                applyMask(doc, dec.mask);
+                // Shadow copies of read metadata stored by pre-2.13.0 writes
+                // stay out of a backup (see stripReservedFields).
+                nlohmann::json data = doc.data();
+                const size_t before = data.size();
+                stripReservedFields(data);
+                if (data.size() != before) doc.set_data(data);
+
+                auto* row = batch.mutable_rows()->add_rows();
+                *row->mutable_document() = toProto(doc);
+                switch (state) {
+                    case VS::Present:  row->set_vector_state(pb::VECTOR_STATE_PRESENT); break;
+                    case VS::None:     row->set_vector_state(pb::VECTOR_STATE_NONE); break;
+                    case VS::Missing:  row->set_vector_state(pb::VECTOR_STATE_MISSING); break;
+                    case VS::Unknown:  row->set_vector_state(pb::VECTOR_STATE_UNKNOWN); break;
+                    default:           row->set_vector_state(pb::VECTOR_STATE_UNSPECIFIED); break;
+                }
+                if (vec && n > 0) {
+                    row->mutable_document()->set_vector(
+                        std::string(reinterpret_cast<const char*>(vec), n * sizeof(float)));
+                }
+                batchBytes += row->ByteSizeLong();
+                if (batch.rows().rows_size() >= static_cast<int>(batchRows) ||
+                    batchBytes >= kExportMaxBatchBytes) {
+                    if (!flush()) {
+                        writeFailed = true;
+                        return false;
+                    }
+                }
+                return true;
+            });
+        if (!found) {
+            return grpc::Status(grpc::StatusCode::NOT_FOUND,
+                                "no collection named '" + collection + "'");
+        }
+    } catch (const std::exception& e) {
+        spdlog::error("ExportCollection {} failed: {}", collection, e.what());
+        return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
+    }
+    if (writeFailed || !flush()) {
+        return grpc::Status(grpc::StatusCode::CANCELLED, "the client stopped reading the export");
+    }
+    if (shuttingDown_.load()) {
+        // The trailer is still sent, so the caller gets a resume cursor.
+        spdlog::info("ExportCollection {} cut short by shutdown after {} rows", collection, rowsSent);
+    }
+
+    pb::ExportChunk tail;
+    auto* t = tail.mutable_trailer();
+    t->set_rows_sent(rowsSent);
+    t->set_last_id(lastId);
+    t->set_complete(!stoppedEarly);
+    writer->Write(tail);
+    return grpc::Status::OK;
+}
+
 // ===== Set Operations =====
 
 grpc::Status DatabaseGrpcImpl::SetAdd(
@@ -2928,6 +3120,22 @@ grpc::Status DatabaseGrpcImpl::GetMemoryStats(
 
 // ===== Helper Methods =====
 
+// v2.13.0 - Get/Find with include_vector: the stored vector as raw float32
+// bytes. Read from the LMDB store (the vector sub-db is the durable copy); when
+// the store is degraded or the row has no vector, the field stays empty and
+// the client reports no `_vector`.
+void DatabaseGrpcImpl::attachStoredVector(pb::Document& protoDoc,
+                                          const std::string& collection) {
+    if (!service_.mirrorHealthy() || service_.mirrorDriftCount() != 0) return;
+    const auto rc = smartbotic::database::resolveCollection(collection);
+    auto* ds = service_.docStore(rc.project);
+    if (!ds) return;
+    if (auto vec = ds->get_vector(rc.collection, protoDoc.id()); vec && !vec->empty()) {
+        protoDoc.set_vector(std::string(reinterpret_cast<const char*>(vec->data()),
+                                        vec->size() * sizeof(float)));
+    }
+}
+
 pb::Document DatabaseGrpcImpl::toProto(const Document& doc) {
     pb::Document proto;
     proto.set_id(doc.id);

+ 13 - 0
service/src/database_grpc_impl.hpp

@@ -173,6 +173,13 @@ public:
         pb::SimilaritySearchResponse* response
     ) override;
 
+    // v2.13.0 - stream one collection out (documents + optional vectors).
+    grpc::Status ExportCollection(
+        grpc::ServerContext* context,
+        const pb::ExportRequest* request,
+        grpc::ServerWriter<pb::ExportChunk>* writer
+    ) override;
+
     // ===== Set Operations =====
 
     grpc::Status SetAdd(
@@ -450,6 +457,7 @@ public:
 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
     static Document fromProto(const pb::Document& proto);
     static pb::CollectionInfo toProtoCollInfo(const struct CollectionInfo& info);
     static pb::DocumentVersionEntry toProtoVersionEntry(const DocumentVersion& ver);
@@ -632,6 +640,11 @@ private:
     std::atomic<uint32_t> activeFileStreams_{0};
     uint32_t maxSubscribeStreams_ = 50;
     uint32_t maxFileStreams_ = 10;
+    // v2.13.0 - each export holds an LMDB read transaction for its whole life,
+    // and LMDB has a fixed reader table (126 by default), so the number of
+    // concurrent exports is capped well below it.
+    std::atomic<uint32_t> activeExportStreams_{0};
+    uint32_t maxExportStreams_ = 8;
 };
 
 /**

+ 33 - 0
service/src/document.hpp

@@ -11,6 +11,29 @@
 
 namespace smartbotic::database {
 
+/**
+ * v2.13.0 - the metadata names a read attaches to every document. They live
+ * on the Document, never in its data, so a write body carrying them (a row read
+ * back and written again, which is exactly what an export -> import does) must
+ * not store them. Before 2.13.0 insert/upsert/update/patch stored them as
+ * ordinary user fields that every read then hid by overwriting them with the
+ * real metadata: invisible, unfilterable (a filter on `_version` resolves to
+ * the metadata), and carried into every later export. Nothing could depend on
+ * the stored copies, since no read path ever showed them.
+ */
+inline bool isReservedField(std::string_view key) {
+    return key == "_id" || key == "_version" || key == "_created_at" ||
+           key == "_updated_at" || key == "_created_by" || key == "_updated_by";
+}
+
+/** Remove the reserved metadata names from a top-level write body. */
+inline void stripReservedFields(nlohmann::json& body) {
+    if (!body.is_object()) return;
+    for (auto it = body.begin(); it != body.end();) {
+        if (isReservedField(it.key())) it = body.erase(it); else ++it;
+    }
+}
+
 /**
  * Represents a document stored in a collection.
  * Documents are JSON objects with metadata for versioning, TTL, and encryption.
@@ -35,6 +58,12 @@ struct Document {
     std::string createdBy;                       // User ID who created the document
     std::string updatedBy;                       // User ID who last updated the document
     uint64_t lastAccessedAt = 0;                 // Last read access timestamp (for LRU eviction)
+    // v2.13.0 - whether this document's last write left it with a stored
+    // vector. Recorded only in collections with a vector dimension; absent on
+    // rows written before 2.13.0. It lets an export tell a row that never had a
+    // vector (false) from one whose vector entry is gone (true, no entry) - the
+    // stored body alone cannot, because `_vector` is stripped on write.
+    std::optional<bool> hasVector;
 
     // Lazy full-tree accessor. Materialises on first call, returns cached
     // reference thereafter. Cost: one decode() pass plus the cache memory.
@@ -107,6 +136,7 @@ struct Document {
         j["createdBy"] = createdBy;
         j["updatedBy"] = updatedBy;
         j["lastAccessedAt"] = lastAccessedAt;
+        if (hasVector) j["hasVector"] = *hasVector;   // v2.13.0
         return j;
     }
 
@@ -132,6 +162,9 @@ struct Document {
         } else {
             doc.lastAccessedAt = doc.updatedAt > 0 ? doc.updatedAt : doc.createdAt;
         }
+        if (auto h = j.find("hasVector"); h != j.end() && h->is_boolean()) {
+            doc.hasVector = h->get<bool>();   // v2.13.0
+        }
         return doc;
     }
 };

+ 35 - 31
service/src/memory_store.cpp

@@ -357,6 +357,7 @@ std::string MemoryStore::insert(const std::string& collection, Document doc) {
 
     // Extract vector before storing document (strips _vector from JSON data)
     auto vec = extractVector(*coll, doc);
+    const auto vc = replaceVectorChange(*coll, vec, doc);   // v2.13.0
 
     // Set metadata
     doc.collection = collection;
@@ -397,10 +398,7 @@ std::string MemoryStore::insert(const std::string& collection, Document doc) {
             removeVector(*coll, docId);
         }
         coll->documents.erase(docId);
-    });
-    if (!vec.empty()) {
-        mirrorVectorToDocStore(collection, docId, &vec, EventType::INSERT);
-    }
+    }, vc);   // v2.13.0 - the vector commits with the document
 
     lock.unlock();
 
@@ -554,6 +552,7 @@ bool MemoryStore::update(const std::string& collection, const std::string& id, c
 
     // Extract vector before storing document (strips _vector from JSON data)
     auto vec = extractVector(*coll, updated);
+    const auto vc = replaceVectorChange(*coll, vec, updated);   // v2.13.0
 
     updated.id = id;
     updated.collection = collection;
@@ -632,12 +631,7 @@ bool MemoryStore::update(const std::string& collection, const std::string& id, c
         } else {
             removeVector(*coll, id);
         }
-    });
-    if (!vec.empty()) {
-        mirrorVectorToDocStore(collection, id, &vec, EventType::UPDATE);
-    } else {
-        mirrorVectorToDocStore(collection, id, nullptr, EventType::DELETE);
-    }
+    }, vc);   // v2.13.0 - the vector commits with the document
 
     lock.unlock();
 
@@ -689,6 +683,7 @@ std::string MemoryStore::upsert(const std::string& collection, Document doc) {
 
     // Extract vector before storing document (strips _vector from JSON data)
     auto vec = extractVector(*coll, doc);
+    const auto vc = replaceVectorChange(*coll, vec, doc);   // v2.13.0
 
     std::string docId = doc.id;
     bool isInsert = false;
@@ -808,13 +803,7 @@ std::string MemoryStore::upsert(const std::string& collection, Document doc) {
                 removeVector(*coll, docId);
             }
         }
-    });
-    if (!vec.empty()) {
-        mirrorVectorToDocStore(collection, docId, &vec,
-                               isInsert ? EventType::INSERT : EventType::UPDATE);
-    } else if (!isInsert) {
-        mirrorVectorToDocStore(collection, docId, nullptr, EventType::DELETE);
-    }
+    }, vc);   // v2.13.0 - the vector commits with the document
 
     lock.unlock();
 
@@ -1274,6 +1263,7 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
     // collection (the v2.0 mirror made the divergence observable
     // across handlers).
     auto vec = extractVector(*coll, updated);
+    const auto vc = replaceVectorChange(*coll, vec, updated);   // v2.13.0
 
     // Add to new expiration index
     if (updated.expiresAt > 0) {
@@ -1325,12 +1315,7 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
         } else {
             removeVector(*coll, id);
         }
-    });
-    if (!vec.empty()) {
-        mirrorVectorToDocStore(collection, id, &vec, EventType::UPDATE);
-    } else {
-        mirrorVectorToDocStore(collection, id, nullptr, EventType::DELETE);
-    }
+    }, vc);   // v2.13.0 - the vector commits with the document
 
     lock.unlock();
 
@@ -1564,7 +1549,11 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
     auto vec = extractVector(*coll, it->second);
     if (!vec.empty()) {
         storeVector(*coll, id, vec);
+        it->second.hasVector = true;   // v2.13.0 - only a supplied vector changes it
     }
+    // v2.13.0 - a patch without `_vector` keeps both the vector and its marker.
+    const auto vc = vec.empty() ? smartbotic::db::storage::VectorChange::keep()
+                                : smartbotic::db::storage::VectorChange::put(vec);
 
     // Update metadata
     it->second.version++;
@@ -1629,10 +1618,7 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
                 removeVector(*coll, id);
             }
         }
-    });
-    if (!vec.empty()) {
-        mirrorVectorToDocStore(collection, id, &vec, EventType::UPDATE);
-    }
+    }, vc);   // v2.13.0 - the vector commits with the document
 
     lock.unlock();
 
@@ -3018,6 +3004,9 @@ uint64_t MemoryStore::restoreToVersion(const std::string& collection, const std:
         restoredDoc.encrypted = targetVer.encrypted;
         restoredDoc.encryptedFields = targetVer.encryptedFields;
         restoredDoc.nodeId = config_.nodeId;
+        // v2.13.0 - the delete removed the vector, and a restore does not bring
+        // one back, so the recreated row truthfully has none.
+        if (coll->options.vectorDimension > 0) restoredDoc.hasVector = false;
 
         // Apply default TTL if configured
         if (coll->options.defaultTtlSeconds > 0) {
@@ -3468,7 +3457,8 @@ void MemoryStore::setDocumentStoreMirror(DocumentStoreResolver resolver,
 }
 
 void MemoryStore::mirrorWriteToDocStore(const std::string& collection, const std::string& id,
-                                         const std::optional<Document>& doc, EventType eventType) {
+                                         const std::optional<Document>& doc, EventType eventType,
+                                         const smartbotic::db::storage::VectorChange& vc) {
     if (!docStoreResolver_ || !mirrorHealthy_ || !mirrorDriftCount_) return;
     // v2.3 — collection is the qualified form "project:collection". Parse
     // it to route to the right project's LMDB env; the unqualified piece
@@ -3478,7 +3468,20 @@ void MemoryStore::mirrorWriteToDocStore(const std::string& collection, const std
     if (!ds) return;
     smartbotic::db::storage::applyDualWriteMirror(
         ds, *mirrorHealthy_, *mirrorDriftCount_,
-        pc.collection, id, doc, eventType);
+        pc.collection, id, doc, eventType, vc);
+}
+
+smartbotic::db::storage::VectorChange
+MemoryStore::replaceVectorChange(const CollectionData& coll, const std::vector<float>& vec,
+                                 Document& doc) {
+    using smartbotic::db::storage::VectorChange;
+    if (coll.options.vectorDimension == 0) {
+        // No vector index: extractVector() left any `_vector` in the body and
+        // nothing is ever stored in the vector sub-db. Record no marker.
+        return VectorChange::keep();
+    }
+    doc.hasVector = !vec.empty();
+    return vec.empty() ? VectorChange::remove() : VectorChange::put(vec);
 }
 
 bool MemoryStore::needsUndoSnapshot(const std::string& collection) const {
@@ -3499,9 +3502,10 @@ bool MemoryStore::needsUndoSnapshot(const std::string& collection) const {
 
 void MemoryStore::mirrorDocOrUndo(const std::string& collection, const std::string& id,
                                    const Document& doc, EventType eventType,
-                                   const std::function<void()>& undo) {
+                                   const std::function<void()>& undo,
+                                   const smartbotic::db::storage::VectorChange& vc) {
     try {
-        mirrorWriteToDocStore(collection, id, doc, eventType);
+        mirrorWriteToDocStore(collection, id, doc, eventType, vc);
     } catch (const smartbotic::db::storage::UniqueViolation&) {
         undo();
         throw;

+ 18 - 2
service/src/memory_store.hpp

@@ -1,6 +1,7 @@
 #pragma once
 
 #include "document.hpp"
+#include "storage/vector_change.hpp"
 
 #include <atomic>
 #include <deque>
@@ -1241,8 +1242,12 @@ private:
     // any subsequent LMDB read by any thread observes the same state as
     // a MemoryStore read. No-op when setDocumentStoreMirror() hasn't been
     // called (legacy / test bootstrap path).
+    // v2.13.0 - `vc` carries the write's effect on the stored vector so the
+    // document and its vector commit in ONE LMDB transaction.
     void mirrorWriteToDocStore(const std::string& collection, const std::string& id,
-                                const std::optional<Document>& doc, EventType eventType);
+                                const std::optional<Document>& doc, EventType eventType,
+                                const smartbotic::db::storage::VectorChange& vc =
+                                    smartbotic::db::storage::VectorChange::keep());
 
     // v2.11.0 T11 — mirrors an INSERT/UPDATE doc write, and on a rejected
     // UniqueViolation runs `undo` (which must restore CollectionData to its
@@ -1263,7 +1268,18 @@ private:
     // delete cannot raise UniqueViolation.
     void mirrorDocOrUndo(const std::string& collection, const std::string& id,
                          const Document& doc, EventType eventType,
-                         const std::function<void()>& undo);
+                         const std::function<void()>& undo,
+                         const smartbotic::db::storage::VectorChange& vc =
+                             smartbotic::db::storage::VectorChange::keep());
+
+    // v2.13.0 - the vector change for a replace-style write (insert, update,
+    // upsert) given the vector extracted from its body, and the marker it
+    // records. In a vector collection a body without `_vector` REMOVES the
+    // stored vector (update replaces the whole document), so the marker
+    // becomes false; collections without a dimension record nothing.
+    static smartbotic::db::storage::VectorChange
+    replaceVectorChange(const CollectionData& coll, const std::vector<float>& vec,
+                        Document& doc);
 
     // v2.0 Stage 5 — mirror a vector write/delete into the LMDB sub-db
     // `_vectors_<collection>`. Called from within the per-collection

+ 49 - 0
service/src/storage/document_store.hpp

@@ -21,11 +21,13 @@
 #include <cstdint>
 #include <functional>
 #include <optional>
+#include <stdexcept>
 #include <string>
 #include <string_view>
 #include <vector>
 
 #include "document.hpp"
+#include "storage/vector_change.hpp"
 
 namespace smartbotic::db::storage {
 
@@ -174,6 +176,53 @@ public:
         std::function<void(std::string_view id,
                            const float* data,
                            size_t count)> /*callback*/) {}
+
+    // v2.13.0 - ExportCollection. Walks one collection in id order inside ONE
+    // read transaction, so a stream is an exact snapshot: no row is skipped or
+    // repeated within it. Rows with an id <= `after_id` are skipped (resume).
+    //
+    // `include`, when set, decides per row whether the caller may see it (a
+    // policy row predicate); it is applied in the counting pass too, so the
+    // count handed to `on_start` is exactly the number of rows `on_row` will be
+    // offered if the walk is not stopped.
+    //
+    // With `with_vectors` each row also gets its vector state, read from the
+    // `_vectors_<collection>` sub-db in the same transaction: Present (with the
+    // bytes), else the document's marker decides - None (written without a
+    // vector), Missing (written WITH one and the entry is gone), Unknown (a row
+    // from before the marker existed). `vec` is valid only during the call.
+    //
+    // `on_row` returns false to stop the walk (time cap, cancelled client).
+    // Returns false only when the collection does not exist.
+    enum class ExportVectorState { Unspecified, Present, None, Missing, Unknown };
+    virtual bool export_scan(
+        std::string_view /*collection*/,
+        std::string_view /*after_id*/,
+        bool /*with_vectors*/,
+        const std::function<bool(const smartbotic::database::Document&)>& /*include*/,
+        const std::function<void(uint64_t rows)>& /*on_start*/,
+        const std::function<bool(smartbotic::database::Document&& doc,
+                                 ExportVectorState state,
+                                 const float* vec, size_t n)>& /*on_row*/) {
+        throw std::runtime_error("export is not supported by this document store");
+    }
+
+    // v2.13.0 - write a document and apply its vector change together. The
+    // LMDB store overrides this with ONE transaction, so no reader sees the
+    // document without its vector or with the previous one. This default,
+    // for stores with no shared transaction (unit tests), applies the steps
+    // in order, document first.
+    virtual void put_with_vector(std::string_view collection,
+                                 std::string_view id,
+                                 const smartbotic::database::Document& doc,
+                                 const VectorChange& vc) {
+        put(collection, id, doc);
+        if (vc.kind == VectorChange::Kind::Put && vc.vec && !vc.vec->empty()) {
+            put_vector(collection, id, *vc.vec);
+        } else if (vc.kind == VectorChange::Kind::Remove) {
+            del_vector(collection, id);
+        }
+    }
 };
 
 }  // namespace smartbotic::db::storage

+ 125 - 0
service/src/storage/document_store_lmdb.cpp

@@ -530,6 +530,23 @@ void LmdbDocumentStore::put(std::string_view collection,
     for (const auto& [sub, d] : to_cache) cacheCommittedDbi(sub, d);
 }
 
+void LmdbDocumentStore::put_with_vector(std::string_view collection,
+                                        std::string_view id,
+                                        const smartbotic::database::Document& doc,
+                                        const VectorChange& vc) {
+    WriteTxn wtxn(env_);
+    std::vector<std::pair<std::string, unsigned int>> to_cache;
+    put(wtxn, collection, id, doc, to_cache);
+    if (vc.kind == VectorChange::Kind::Put && vc.vec && !vc.vec->empty()) {
+        put_vector(wtxn, collection, id, *vc.vec, to_cache);
+    } else if (vc.kind == VectorChange::Kind::Remove) {
+        del_vector(wtxn, collection, id, to_cache);
+    }
+    // Commit BEFORE any handle is cached - the v2.8.0 lesson.
+    wtxn.commit();
+    for (const auto& [sub, d] : to_cache) cacheCommittedDbi(sub, d);
+}
+
 void LmdbDocumentStore::put_batch(const std::vector<BatchPutItem>& items) {
     if (items.empty()) return;
     WriteTxn wtxn(env_);
@@ -1772,6 +1789,114 @@ uint64_t LmdbDocumentStore::count(std::string_view collection) {
 // counts it, so comparing a raw ms_entries against an index's posting count is
 // off by exactly one - which silently disabled the ordered plan in every case
 // until a test asserted the plan was actually taken.
+namespace {
+std::string vector_subdb_name(std::string_view collection);   // defined with the vector ops below
+}  // namespace
+
+bool LmdbDocumentStore::export_scan(
+        std::string_view collection,
+        std::string_view after_id,
+        bool with_vectors,
+        const std::function<bool(const smartbotic::database::Document&)>& include,
+        const std::function<void(uint64_t rows)>& on_start,
+        const std::function<bool(smartbotic::database::Document&& doc,
+                                 ExportVectorState state,
+                                 const float* vec, size_t n)>& on_row) {
+    // ONE read transaction for the count and the walk: that is what makes a
+    // stream an exact snapshot, and what makes the count a checksum for it.
+    ReadTxn rtxn(env_);
+    auto dbi_opt = try_open_for_read(rtxn, collection);
+    if (!dbi_opt) return false;
+    std::optional<unsigned int> vdbi;
+    if (with_vectors) vdbi = try_open_for_read(rtxn, vector_subdb_name(collection));
+
+    MDB_cursor* cursor = nullptr;
+    mdb_check(mdb_cursor_open(rtxn.raw(), *dbi_opt, &cursor), "cursor_open (export)");
+    struct CursorGuard {
+        MDB_cursor* c;
+        ~CursorGuard() { if (c) mdb_cursor_close(c); }
+    } guard{cursor};
+
+    // Position on the first key strictly after `after_id`, skipping the
+    // identity sentinel wherever it sorts.
+    auto first = [&](MDB_val& k, MDB_val& v) -> int {
+        int rc;
+        if (after_id.empty()) {
+            rc = mdb_cursor_get(cursor, &k, &v, MDB_FIRST);
+        } else {
+            k = to_val(after_id);
+            rc = mdb_cursor_get(cursor, &k, &v, MDB_SET_RANGE);
+            if (rc == MDB_SUCCESS && to_sv(k) == after_id) {
+                rc = mdb_cursor_get(cursor, &k, &v, MDB_NEXT);
+            }
+        }
+        while (rc == MDB_SUCCESS && is_identity_key(to_sv(k))) {
+            rc = mdb_cursor_get(cursor, &k, &v, MDB_NEXT);
+        }
+        return rc;
+    };
+    auto next = [&](MDB_val& k, MDB_val& v) -> int {
+        int rc = mdb_cursor_get(cursor, &k, &v, MDB_NEXT);
+        while (rc == MDB_SUCCESS && is_identity_key(to_sv(k))) {
+            rc = mdb_cursor_get(cursor, &k, &v, MDB_NEXT);
+        }
+        return rc;
+    };
+
+    MDB_val k{0, nullptr};
+    MDB_val v{0, nullptr};
+
+    // Pass 1 - count. Free when the whole collection is wanted and no policy
+    // filters it; otherwise walk the keys (decoding only under a predicate).
+    uint64_t rows = 0;
+    if (after_id.empty() && !include) {
+        rows = rowCountTxn(rtxn, *dbi_opt);
+    } else {
+        int rc = first(k, v);
+        while (rc == MDB_SUCCESS) {
+            if (!include || include(decode_document(to_sv(v)))) ++rows;
+            rc = next(k, v);
+        }
+        if (rc != MDB_NOTFOUND) throw_mdb(rc, "cursor_get (export count)");
+    }
+    on_start(rows);
+
+    // Pass 2 - the rows, in id order.
+    int rc = first(k, v);
+    while (rc == MDB_SUCCESS) {
+        smartbotic::database::Document doc = decode_document(to_sv(v));
+        if (!include || include(doc)) {
+            ExportVectorState state = ExportVectorState::Unspecified;
+            const float* data = nullptr;
+            size_t n = 0;
+            if (with_vectors) {
+                MDB_val vk = to_val(to_sv(k));
+                MDB_val vv{0, nullptr};
+                const int vrc = vdbi ? mdb_get(rtxn.raw(), *vdbi, &vk, &vv) : MDB_NOTFOUND;
+                if (vrc == MDB_SUCCESS) {
+                    if (vv.mv_size % sizeof(float) != 0) {
+                        throw std::runtime_error(
+                            "export: stored vector bytes are not a multiple of sizeof(float)");
+                    }
+                    state = ExportVectorState::Present;
+                    data = static_cast<const float*>(vv.mv_data);
+                    n = vv.mv_size / sizeof(float);
+                } else if (vrc == MDB_NOTFOUND) {
+                    state = !doc.hasVector ? ExportVectorState::Unknown
+                          : *doc.hasVector ? ExportVectorState::Missing
+                                           : ExportVectorState::None;
+                } else {
+                    throw_mdb(vrc, "get (export vector)");
+                }
+            }
+            if (!on_row(std::move(doc), state, data, n)) return true;
+        }
+        rc = next(k, v);
+    }
+    if (rc != MDB_NOTFOUND) throw_mdb(rc, "cursor_get (export)");
+    return true;
+}
+
 uint64_t LmdbDocumentStore::rowCountTxn(ReadTxn& rtxn, unsigned int dbi) {
     MDB_stat st{};
     if (mdb_stat(rtxn.raw(), dbi, &st) != MDB_SUCCESS) return 0;

+ 19 - 0
service/src/storage/document_store_lmdb.hpp

@@ -510,6 +510,25 @@ public:
     // aborts everything done through it — nothing partial can survive.
     class WriteTxn beginWrite();
 
+    // v2.13.0 - see DocumentStore::export_scan.
+    bool export_scan(
+        std::string_view collection,
+        std::string_view after_id,
+        bool with_vectors,
+        const std::function<bool(const smartbotic::database::Document&)>& include,
+        const std::function<void(uint64_t rows)>& on_start,
+        const std::function<bool(smartbotic::database::Document&& doc,
+                                 ExportVectorState state,
+                                 const float* vec, size_t n)>& on_row) override;
+
+    // v2.13.0 - see DocumentStore::put_with_vector: the document, its index
+    // maintenance and its vector change in ONE WriteTxn, then commit, then
+    // cache.
+    void put_with_vector(std::string_view collection,
+                         std::string_view id,
+                         const smartbotic::database::Document& doc,
+                         const VectorChange& vc) override;
+
     // v2.11.0 T12 — commit `wtxn`, then cache every handle accumulated in
     // `to_cache`, in that order. Companion to beginWrite(): the same
     // commit-then-cache discipline every no-txn wrapper in this file

+ 14 - 1
service/src/storage/dual_write_mirror.hpp

@@ -28,6 +28,7 @@
 #include "memory_store.hpp"
 #include "storage/document_store.hpp"
 #include "storage/document_store_lmdb.hpp"
+#include "storage/vector_change.hpp"
 
 namespace smartbotic::db::storage {
 
@@ -38,12 +39,24 @@ inline void applyDualWriteMirror(
     const std::string& collection,
     const std::string& id,
     const std::optional<smartbotic::database::Document>& doc,
-    smartbotic::database::EventType eventType) {
+    smartbotic::database::EventType eventType,
+    const VectorChange& vc = VectorChange::keep()) {
 
     if (!doc_store) return;
     if (collection.empty() || collection[0] == '_') return;
 
+    const bool isWrite = eventType == smartbotic::database::EventType::INSERT ||
+                         eventType == smartbotic::database::EventType::UPDATE;
+    const bool touchesVector = isWrite && vc.kind != VectorChange::Kind::Keep;
+
     try {
+        // v2.13.0 - document + vector in one transaction (the LMDB store's
+        // put_with_vector). A refusal (UniqueViolation, MissingParentReference)
+        // aborts both, exactly as a refused document write left no vector.
+        if (touchesVector && doc) {
+            doc_store->put_with_vector(collection, id, *doc, vc);
+            return;
+        }
         switch (eventType) {
             case smartbotic::database::EventType::INSERT:
             case smartbotic::database::EventType::UPDATE:

+ 28 - 0
service/src/storage/vector_change.hpp

@@ -0,0 +1,28 @@
+// v2.13.0 - what a document write does to its stored vector.
+//
+// Passed with the document so both land in ONE LMDB transaction (see
+// applyDualWriteMirror). Before 2.13.0 the document and its vector were two
+// separate commits, so a reader between them saw a fresh insert with no vector
+// (unsearchable for a moment, and an export would have reported it as a lost
+// vector) or an update's new body with the old vector.
+//
+// Keep = the write does not touch the vector: patch without `_vector`, set
+// operations, version restore, replication apply, the re-mirror passes.
+
+#pragma once
+
+#include <vector>
+
+namespace smartbotic::db::storage {
+
+struct VectorChange {
+    enum class Kind { Keep, Put, Remove };
+    Kind kind = Kind::Keep;
+    const std::vector<float>* vec = nullptr;   // Put only; must outlive the call
+
+    static VectorChange keep() { return {}; }
+    static VectorChange put(const std::vector<float>& v) { return {Kind::Put, &v}; }
+    static VectorChange remove() { return {Kind::Remove, nullptr}; }
+};
+
+}  // namespace smartbotic::db::storage

+ 27 - 0
tests/CMakeLists.txt

@@ -559,6 +559,33 @@ endif()
 
 add_test(NAME test_subdb_identity COMMAND test_subdb_identity)
 
+# v2.13.0 - export_scan vector states (incl. MISSING/UNKNOWN, which only a
+# direct write can produce), resume cursor, count, and put_with_vector.
+add_executable(test_export_scan
+    test_export_scan.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/lmdb_env.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/lmdb_txn.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/lmdb_dbi.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/subdb_identity.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/document_store_lmdb.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/relations/relation_index.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/storage/secondary_index.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/json_parse.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/doc_binary.cpp
+)
+target_include_directories(test_export_scan PRIVATE
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src
+    ${LMDB_INCLUDE_DIR}
+    ${yyjson_INCLUDE_DIRS}
+)
+target_link_libraries(test_export_scan PRIVATE ${LMDB_LIBRARY} ${yyjson_LIBRARIES})
+if(TARGET nlohmann_json::nlohmann_json)
+    target_link_libraries(test_export_scan PRIVATE nlohmann_json::nlohmann_json)
+else()
+    target_include_directories(test_export_scan PRIVATE ${NLOHMANN_JSON_INCLUDE_DIRS})
+endif()
+add_test(NAME test_export_scan COMMAND test_export_scan)
+
 # v2.11.0 T2 — relation reverse index (parent id -> child ids, DUPSORT).
 # Only the sources relation_index_{add,remove,child_count,children} actually
 # need: the LMDB store itself plus its direct dependencies. No relations/

+ 370 - 0
tests/load_test/test_export.cpp

@@ -0,0 +1,370 @@
+// v2.13.0 client/server boundary test: reading stored vectors back, and
+// exporting a collection so that the export is a real backup.
+//
+// Requested by smartbotic-vectorapi: nothing returned a stored embedding, so an
+// export of a vector collection would silently produce rows that re-import as
+// unsearchable JSON. Phases, run by test_export.sh:
+//   write  - seed: rows with vectors, rows written without, rows whose vector
+//            an update removed, rows a patch left alone, a body carrying the
+//            six reserved read-metadata names, a collection with no dimension.
+//   check  - get/find WithVector; the export contract (header, clamp, order,
+//            count, states, exact vectors); THE ROUND TRIP (export -> insert
+//            into an empty collection -> same fields, same vectors, each row
+//            its own nearest neighbour, fresh metadata); resume; refusals; the
+//            file Failure& overloads; a throwing event handler.
+//   after  - after a restart, the states are unchanged (the has-vector marker
+//            persisted through WAL/snapshot and the LMDB envelope).
+//   race   - exports run while vectors are being inserted: every row a stream
+//            sees must be PRESENT. Before 2.13.0 a document and its vector were
+//            two commits, so a snapshot between them saw the row without it.
+//   down   - server stopped: every new call reports Unavailable.
+
+#include <smartbotic/database/client.hpp>
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <iostream>
+#include <random>
+#include <set>
+#include <string>
+#include <thread>
+#include <vector>
+
+using namespace smartbotic::database;
+using VS = Client::VectorState;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+static const char* kAddr = "127.0.0.1:9023";
+static const uint32_t kDim = 4;
+
+static std::vector<float> vecFor(int i) {
+    std::mt19937 rng(1000 + i);
+    std::normal_distribution<float> nd(0.f, 1.f);
+    std::vector<float> v(kDim);
+    for (auto& x : v) x = nd(rng);
+    return v;
+}
+static std::string id3(const char* p, int i) {
+    char b[16];
+    std::snprintf(b, sizeof b, "%s%03d", p, i);
+    return b;
+}
+static nlohmann::json userFields(nlohmann::json d) {
+    for (const char* k : {"_id", "_version", "_created_at", "_updated_at", "_created_by",
+                          "_updated_by", "_vector"}) {
+        d.erase(k);
+    }
+    return d;
+}
+
+struct Export {
+    Client::ExportHeader header;
+    std::vector<Client::ExportRow> rows;
+    Client::ExportSummary summary;
+};
+static Export runExport(Client& c, const std::string& coll, bool vectors,
+                        const std::string& after = "", size_t stopAfter = 0,
+                        uint32_t batchRows = 0) {
+    Export e;
+    e.summary = c.exportCollection(
+        coll, vectors, after, [&](const Client::ExportHeader& h) { e.header = h; },
+        [&](Client::ExportRow&& r) {
+            e.rows.push_back(std::move(r));
+            return stopAfter == 0 || e.rows.size() < stopAfter;
+        },
+        batchRows);
+    return e;
+}
+
+static Client::Config cfg() {
+    Client::Config c;
+    c.address = kAddr;
+    c.project = "ex";
+    return c;
+}
+
+static int write() {
+    Client c(cfg());
+    c.connect();
+    ck(c.createCollection("vecs", 0, false, 0, kDim), "create vecs (dim 4)");
+    for (int i = 0; i < 400; ++i) {
+        c.insert("vecs", {{"n", i}, {"s", "row " + std::to_string(i)}, {"_vector", vecFor(i)}},
+                 id3("v", i));
+    }
+    for (int i = 0; i < 40; ++i) c.insert("vecs", {{"n", 1000 + i}}, id3("w", i));
+    for (int i = 0; i < 20; ++i) {
+        c.insert("vecs", {{"n", 2000 + i}, {"_vector", vecFor(2000 + i)}}, id3("u", i));
+        ck(c.update("vecs", id3("u", i), {{"n", 2000 + i}, {"updated", true}}),
+           "update without _vector");
+    }
+    for (int i = 0; i < 20; ++i) {
+        c.insert("vecs", {{"n", 3000 + i}, {"_vector", vecFor(3000 + i)}}, id3("p", i));
+        Client::FailureDetail fd;
+        ck(c.patch("vecs", id3("p", i), {{"patched", true}}, fd) > 0, "patch without _vector");
+    }
+    // A body carrying the six read-metadata names - what a read handed back
+    // and written again looks like.
+    c.insert("vecs", {{"n", 5000}, {"_id", "fake"}, {"_version", 99}, {"_created_at", 5},
+                      {"_updated_at", 6}, {"_created_by", "mallory"}, {"_updated_by", "mallory"},
+                      {"_vector", vecFor(5000)}},
+             "shadow");
+    ck(c.createCollection("plain"), "create plain (no dimension)");
+    for (int i = 0; i < 3; ++i) c.insert("plain", {{"n", i}}, id3("q", i));
+    return 0;
+}
+
+static void check() {
+    Client c(cfg());
+    c.connect();
+
+    // --- get / find WithVector
+    auto g = c.get("vecs", "v007", Client::WithVector{});
+    ck(g && g->contains("_vector") && (*g)["_vector"].get<std::vector<float>>() == vecFor(7),
+       "get WithVector returns the exact stored vector");
+    auto plainGet = c.get("vecs", "v007");
+    ck(plainGet && !plainGet->contains("_vector"), "plain get does not return the vector");
+    auto gw = c.get("vecs", "w003", Client::WithVector{});
+    ck(gw && !gw->contains("_vector"), "get WithVector on a row with no vector: no _vector key");
+    auto gu = c.get("vecs", "u003", Client::WithVector{});
+    ck(gu && !gu->contains("_vector"), "an update without _vector removed the vector");
+    auto gp = c.get("vecs", "p003", Client::WithVector{});
+    ck(gp && (*gp)["_vector"].get<std::vector<float>>() == vecFor(3003) && (*gp)["patched"] == true,
+       "a patch without _vector kept the vector");
+    auto f = c.find("vecs", Client::QueryOptions{.filters = {Client::Filter::lt("n", 5)}},
+                    Client::WithVector{});
+    bool fv = f.size() == 5;
+    for (auto& d : f) {
+        fv = fv && d.contains("_vector") &&
+             d["_vector"].get<std::vector<float>>() == vecFor(d["n"].get<int>());
+    }
+    ck(fv, "find WithVector returns each row's vector");
+
+    // --- reserved names in a write body are not stored
+    auto sh = c.get("vecs", "shadow");
+    ck(sh && (*sh)["_id"] == "shadow" && (*sh)["_version"] == 1 && (*sh)["_created_by"] == "",
+       "read metadata on a row written with fake metadata is the real metadata");
+
+    // --- the export contract
+    const auto exportStart = std::chrono::system_clock::now();
+    auto e = runExport(c, "vecs", true, "", 0, 100000);
+    const uint64_t total = 400 + 40 + 20 + 20 + 1;
+    ck(e.header.vectorDimension == kDim, "header: dimension");
+    ck(e.header.vectorDtype == "float32-le", "header: dtype");
+    ck(e.header.batchRowsEffective == 1024, "header: batch_rows 100000 clamped to 1024");
+    ck(e.header.maxStreamSeconds == 600, "header: stream cap");
+    ck(e.header.rowsAtSnapshot == total, "header: rows at snapshot");
+    ck(e.summary.complete && e.summary.rowsSent == total && e.rows.size() == total,
+       "complete, every row delivered, rowsSent == rowsAtSnapshot");
+    bool ordered = true;
+    for (size_t i = 1; i < e.rows.size(); ++i) ordered = ordered && e.rows[i - 1].id < e.rows[i].id;
+    ck(ordered, "rows in id order, no duplicates");
+    ck(!e.rows.empty() && e.summary.lastId == e.rows.back().id, "lastId is the last row");
+
+    int present = 0, none = 0, other = 0;
+    bool exact = true, idsMatch = true, noShadow = true;
+    for (auto& r : e.rows) {
+        idsMatch = idsMatch && r.document["_id"] == r.id;
+        if (r.id == "shadow") {
+            const std::string dump = r.document.dump();
+            noShadow = dump.find("mallory") == std::string::npos && r.document["_version"] == 1;
+        }
+        const char p = r.id[0];
+        if (p == 'v' || p == 'p' || r.id == "shadow") {
+            if (r.vectorState == VS::Present) ++present; else ++other;
+            const int n = r.document["n"].get<int>();
+            exact = exact && r.vector == vecFor(n);
+        } else {
+            if (r.vectorState == VS::None) ++none; else ++other;
+            exact = exact && r.vector.empty();
+        }
+        exact = exact && !r.document.contains("_vector");
+    }
+    ck(present == 421 && none == 60 && other == 0, "states: 421 present, 60 none, nothing else (" +
+       std::to_string(present) + "/" + std::to_string(none) + "/" + std::to_string(other) + ")");
+    ck(exact, "every vector byte-identical; vector is in row.vector, not the document");
+    ck(idsMatch, "each row's document carries its own _id");
+    ck(noShadow, "no stored shadow metadata in the exported row");
+
+    // --- THE ROUND TRIP: export -> insert into an empty collection
+    ck(c.createCollection("vecs_copy", 0, false, 0, kDim), "create vecs_copy (dim 4)");
+    for (auto& r : e.rows) {
+        nlohmann::json body = r.document;
+        if (r.vectorState == VS::Present) body["_vector"] = r.vector;
+        c.insert("vecs_copy", body, r.id);
+    }
+    auto e2 = runExport(c, "vecs_copy", true);
+    ck(e2.summary.complete && e2.rows.size() == e.rows.size(), "copy has every row");
+    bool same = e2.rows.size() == e.rows.size();
+    bool fresh = same;
+    for (size_t i = 0; same && i < e.rows.size(); ++i) {
+        same = e2.rows[i].id == e.rows[i].id &&
+               userFields(e2.rows[i].document) == userFields(e.rows[i].document) &&
+               e2.rows[i].vectorState == e.rows[i].vectorState &&
+               e2.rows[i].vector == e.rows[i].vector;
+        fresh = fresh && e2.rows[i].document["_version"] == 1 &&
+                e2.rows[i].document["_created_at"].get<uint64_t>() >
+                    e.rows[i].document["_created_at"].get<uint64_t>();
+    }
+    ck(same, "round trip: same ids, same fields, same states, byte-identical vectors");
+    ck(fresh, "restored rows carry FRESH metadata (version 1, newer timestamps)");
+    int nearest = 0;
+    for (int i = 0; i < 400; i += 8) {
+        auto hits = c.similaritySearch("vecs_copy", vecFor(i), 1);
+        if (!hits.empty() && hits[0].id == id3("v", i)) ++nearest;
+    }
+    ck(nearest == 50, "round trip: each sampled row is its own nearest neighbour (" +
+       std::to_string(nearest) + "/50)");
+    (void)exportStart;
+
+    // --- resume
+    auto part = runExport(c, "vecs", false, "", 150);
+    ck(!part.summary.complete && part.summary.rowsSent == 150 && part.summary.lastId == part.rows.back().id,
+       "a handler returning false stops after that row; lastId names it");
+    auto rest = runExport(c, "vecs", false, part.summary.lastId);
+    ck(rest.header.rowsAtSnapshot == total - 150 && rest.summary.complete,
+       "resume counts and completes the rest");
+    std::set<std::string> ids;
+    for (auto& r : part.rows) ids.insert(r.id);
+    for (auto& r : rest.rows) ids.insert(r.id);
+    ck(ids.size() == total && part.rows.size() + rest.rows.size() == total,
+       "first part + resume = every row exactly once");
+    bool unspecified = true;
+    for (auto& r : part.rows) unspecified = unspecified && r.vectorState == VS::Unspecified && r.vector.empty();
+    ck(unspecified, "without vectors: no state, no bytes");
+
+    // --- refusals
+    bool refused = false;
+    std::string reason;
+    try { runExport(c, "plain", true); }
+    catch (const Client::Error& err) {
+        refused = err.code() == Client::ErrorCode::InvalidArgument;
+        if (auto* d = Client::errorDetail(err)) reason = d->reason;
+    }
+    ck(refused && reason == "no_vector_index",
+       "vectors from a collection with no dimension: InvalidArgument, reason no_vector_index");
+    auto pl = runExport(c, "plain", false);
+    ck(pl.summary.complete && pl.rows.size() == 3, "a dimension-0 collection exports without vectors");
+    bool nf = false;
+    try { runExport(c, "no_such_coll", false); }
+    catch (const Client::Error& err) { nf = err.code() == Client::ErrorCode::NotFound; }
+    ck(nf, "export of a missing collection throws NotFound");
+
+    // --- file calls report a reason
+    Client::Failure ff;
+    ck(!c.setFileTtl("no-such-file", 60, ff) && ff.code == Client::ErrorCode::NotFound,
+       "setFileTtl on a missing file: false, NotFound");
+    Client::Failure fd;
+    ck(!c.deleteFile("no-such-file", fd) && fd.code == Client::ErrorCode::NotFound,
+       "deleteFile on a missing file: false, NotFound");
+
+    // --- a throwing event handler drops its event, not the process
+    std::atomic<int> seen{0};
+    auto sub = c.subscribeEvents({"evt"}, [&](const Client::Event&) {
+        if (seen.fetch_add(1) == 0) throw std::runtime_error("handler bug");
+    });
+    std::this_thread::sleep_for(std::chrono::milliseconds(300));
+    c.insert("evt", {{"a", 1}}, "e1");
+    c.insert("evt", {{"a", 2}}, "e2");
+    for (int i = 0; i < 50 && seen.load() < 2; ++i) {
+        std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    }
+    ck(seen.load() == 2, "after a handler threw, the next event still arrived (" +
+       std::to_string(seen.load()) + ")");
+    sub.reset();
+}
+
+static void after() {
+    Client c(cfg());
+    c.connect();
+    auto e = runExport(c, "vecs", true);
+    int present = 0, none = 0, other = 0;
+    for (auto& r : e.rows) {
+        if (r.vectorState == VS::Present) ++present;
+        else if (r.vectorState == VS::None) ++none;
+        else ++other;
+    }
+    ck(e.summary.complete && present == 421 && none == 60 && other == 0,
+       "after a restart the states are unchanged (" + std::to_string(present) + "/" +
+       std::to_string(none) + "/" + std::to_string(other) + ")");
+    auto g = c.get("vecs", "v011", Client::WithVector{});
+    ck(g && (*g)["_vector"].get<std::vector<float>>() == vecFor(11), "vector readable after restart");
+}
+
+static void race() {
+    Client w(cfg());
+    w.connect();
+    w.createCollection("race", 0, false, 0, kDim);
+    std::atomic<bool> done{false};
+    std::thread writer([&]() {
+        for (int i = 0; i < 3000; ++i) {
+            w.insert("race", {{"n", i}, {"_vector", vecFor(i)}}, id3("x", i % 1000) + "-" +
+                     std::to_string(i));
+        }
+        done = true;
+    });
+    Client c(cfg());
+    c.connect();
+    int exports = 0, rows = 0, notPresent = 0;
+    while (!done.load()) {
+        try {
+            auto e = runExport(c, "race", true);
+            ++exports;
+            rows += static_cast<int>(e.rows.size());
+            for (auto& r : e.rows) {
+                if (r.vectorState != VS::Present) {
+                    if (notPresent < 5) {
+                        std::cerr << "  row " << r.id << " state " << static_cast<int>(r.vectorState) << "\n";
+                    }
+                    ++notPresent;
+                }
+            }
+        } catch (const Client::Error& err) {
+            if (err.code() != Client::ErrorCode::NotFound) throw;   // collection not created yet
+        }
+    }
+    writer.join();
+    std::cout << "race: " << exports << " exports, " << rows << " rows seen\n";
+    ck(exports >= 3, "several exports ran during the inserts");
+    ck(notPresent == 0, "no export saw a row without its vector (" + std::to_string(notPresent) + ")");
+}
+
+static void down() {
+    Client::Config cf = cfg();
+    cf.timeoutMs = 700;
+    cf.maxRetries = 0;
+    cf.writeRetries = 0;
+    Client c(cf);
+    c.connect();
+    auto code = [](auto fn) {
+        try { fn(); } catch (const Client::Error& e) { return e.code(); } catch (...) {}
+        return Client::ErrorCode::Ok;
+    };
+    ck(code([&] { (void)c.get("vecs", "v001", Client::WithVector{}); }) == Client::ErrorCode::Unavailable,
+       "down: get WithVector throws Unavailable");
+    ck(code([&] { (void)c.find("vecs", Client::QueryOptions{}, Client::WithVector{}); }) ==
+           Client::ErrorCode::Unavailable,
+       "down: find WithVector throws Unavailable");
+    ck(code([&] { runExport(c, "vecs", true); }) == Client::ErrorCode::Unavailable,
+       "down: export throws Unavailable");
+    Client::Failure f1, f2;
+    ck(!c.setFileTtl("x", 60, f1) && f1.code == Client::ErrorCode::Unavailable,
+       "down: setFileTtl reports Unavailable, not NotFound");
+    ck(!c.deleteFile("x", f2) && f2.code == Client::ErrorCode::Unavailable,
+       "down: deleteFile reports Unavailable, not NotFound");
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "";
+    if (phase == "write") write();
+    else if (phase == "check") check();
+    else if (phase == "after") after();
+    else if (phase == "race") race();
+    else if (phase == "down") down();
+    else { std::cerr << "usage: write|check|after|race|down\n"; return 2; }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 93 - 0
tests/load_test/test_export.sh

@@ -0,0 +1,93 @@
+#!/usr/bin/env bash
+# v2.13.0 client/server boundary e2e - stored vectors read back, and a
+# collection export that round-trips as a backup. See test_export.cpp for what
+# each phase asserts.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-export
+PORT=9023
+
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_export.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+start() {
+    "$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" >> "$DIR/server.log" 2>&1 &
+    SERVER_PID=$!
+    for _ in $(seq 1 60); do
+        [[ $(grep -c "Notified systemd: READY" "$DIR/server.log") -ge $1 ]] && return 0
+        sleep 0.5
+    done
+    tail -30 "$DIR/server.log"
+    exit 1
+}
+stop() {
+    [[ -n "$SERVER_PID" ]] || return 0
+    kill "$SERVER_PID" 2>/dev/null || true
+    wait "$SERVER_PID" 2>/dev/null || true
+    SERVER_PID=""
+}
+trap stop EXIT
+
+run() {
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1" 2>&1 | grep -v '\[error\]' | tee "$DIR/out-$1.txt"
+    local rc=${PIPESTATUS[0]}
+    set -e
+    [[ $rc -eq 0 ]] || { echo "FAILED in phase $1"; exit $rc; }
+}
+
+start 1
+echo "=== write ==="
+run write
+
+# The six read-metadata names in a write body must not be stored. Reads hide
+# them either way, so the only direct evidence is the data on disk.
+echo "=== reserved names are not stored ==="
+if grep -rqa mallory "$DIR/data"; then
+    echo "FAIL: a write body's _created_by/_updated_by value reached the data directory"
+    exit 1
+fi
+echo "PASS: no reserved-name value on disk"
+
+echo "=== check ==="
+run check
+
+echo "=== restart ==="
+stop
+start 2
+echo "=== after restart ==="
+run after
+
+echo "=== race: exports during vector inserts ==="
+run race
+
+echo "=== down ==="
+stop
+run down
+
+echo ""
+echo "OK - export e2e passed"

+ 256 - 0
tests/test_export_scan.cpp

@@ -0,0 +1,256 @@
+// v2.13.0 - LmdbDocumentStore::export_scan and put_with_vector, at the store.
+//
+// The two vector states an export can only report for rows nothing in 2.13.0
+// writes - MISSING (the row was written with a vector and its entry is gone)
+// and UNKNOWN (a row from before the has-vector marker) - are produced here by
+// writing those rows directly. The e2e (test_export.sh) covers the states the
+// server produces itself, over gRPC.
+//
+// Also pinned: id order, the resume cursor (strictly after, never repeating),
+// the count matching what is offered, a row predicate applied to the count
+// too, stopping early, a missing collection, and put_with_vector writing the
+// document and its vector together (and removing the vector).
+
+#include <atomic>
+#include <filesystem>
+#include <iostream>
+#include <string>
+#include <thread>
+#include <unistd.h>
+#include <vector>
+
+#include <nlohmann/json.hpp>
+
+#include "document.hpp"
+#include "storage/document_store_lmdb.hpp"
+#include "storage/lmdb_env.hpp"
+#include "storage/vector_change.hpp"
+
+namespace fs = std::filesystem;
+
+using smartbotic::database::Document;
+using smartbotic::db::storage::DocumentStore;
+using smartbotic::db::storage::LmdbDocumentStore;
+using smartbotic::db::storage::LmdbEnv;
+using smartbotic::db::storage::LmdbEnvOpts;
+using smartbotic::db::storage::VectorChange;
+using VS = DocumentStore::ExportVectorState;
+
+namespace {
+
+int g_pass = 0;
+int g_fail = 0;
+
+void check(bool cond, const std::string& msg) {
+    if (cond) {
+        ++g_pass;
+    } else {
+        ++g_fail;
+        std::cerr << "FAIL: " << msg << "\n";
+    }
+}
+
+struct TmpEnv {
+    std::string path;
+    LmdbEnv env;
+    explicit TmpEnv(const char* tag)
+        : path("/tmp/export-scan-test-" + std::to_string(::getpid()) + "-" + tag),
+          env(LmdbEnvOpts{(fs::remove_all(path), path), 64ULL << 20, 256, 126, false}) {}
+    ~TmpEnv() {
+        std::error_code ec;
+        fs::remove_all(path, ec);
+    }
+};
+
+Document doc(const std::string& id, int n, std::optional<bool> hasVector) {
+    Document d;
+    d.id = id;
+    d.collection = "c";
+    d.set_data(nlohmann::json{{"n", n}});
+    d.hasVector = hasVector;
+    return d;
+}
+
+struct Seen {
+    std::string id;
+    VS state;
+    std::vector<float> vec;
+};
+
+std::vector<Seen> scan(DocumentStore& ds, const std::string& after, bool withVectors,
+                       uint64_t* count = nullptr, size_t stopAfter = 0,
+                       std::function<bool(const Document&)> include = {}) {
+    std::vector<Seen> out;
+    ds.export_scan("c", after, withVectors, include,
+                   [&](uint64_t rows) { if (count) *count = rows; },
+                   [&](Document&& d, VS st, const float* v, size_t n) {
+                       out.push_back({d.id, st, std::vector<float>(v, v + n)});
+                       return stopAfter == 0 || out.size() < stopAfter;
+                   });
+    return out;
+}
+
+void test_vector_states() {
+    TmpEnv t("states");
+    LmdbDocumentStore store(t.env);
+    const std::vector<float> v1{1.f, 2.f, 3.f};
+    // present: written with a vector
+    store.put_with_vector("c", "a-present", doc("a-present", 1, true), VectorChange::put(v1));
+    // none: written without one (marker false)
+    store.put_with_vector("c", "b-none", doc("b-none", 2, false), VectorChange::remove());
+    // missing: marker says it had one, the entry is not there
+    store.put("c", "c-missing", doc("c-missing", 3, true));
+    // unknown: no marker (a pre-2.13.0 row), no entry
+    store.put("c", "d-unknown", doc("d-unknown", 4, std::nullopt));
+    // present beats the marker: a legacy row that does have its entry
+    store.put("c", "e-legacy-present", doc("e-legacy-present", 5, std::nullopt));
+    store.put_vector("c", "e-legacy-present", v1);
+
+    uint64_t count = 0;
+    auto rows = scan(store, "", true, &count);
+    check(count == 5, "count is every row");
+    check(rows.size() == 5, "every row offered");
+    if (rows.size() == 5) {
+        check(rows[0].id == "a-present" && rows[0].state == VS::Present, "present");
+        check(rows[0].vec == v1, "present carries the exact vector");
+        check(rows[1].id == "b-none" && rows[1].state == VS::None, "none");
+        check(rows[1].vec.empty(), "none carries no vector");
+        check(rows[2].id == "c-missing" && rows[2].state == VS::Missing, "missing");
+        check(rows[3].id == "d-unknown" && rows[3].state == VS::Unknown, "unknown");
+        check(rows[4].id == "e-legacy-present" && rows[4].state == VS::Present,
+              "a legacy row with its entry is present");
+    }
+    auto noVec = scan(store, "", false);
+    bool allUnspecified = !noVec.empty();
+    for (auto& r : noVec) allUnspecified = allUnspecified && r.state == VS::Unspecified && r.vec.empty();
+    check(allUnspecified, "without vectors: no state, no bytes");
+}
+
+void test_put_with_vector_replaces_and_removes() {
+    TmpEnv t("pwv");
+    LmdbDocumentStore store(t.env);
+    store.put_with_vector("c", "x", doc("x", 1, true), VectorChange::put({1.f, 0.f}));
+    store.put_with_vector("c", "x", doc("x", 2, true), VectorChange::put({0.f, 1.f}));
+    auto v = store.get_vector("c", "x");
+    check(v && *v == std::vector<float>{0.f, 1.f}, "put_with_vector replaces the vector");
+    auto d = store.get("c", "x");
+    check(d && d->data()["n"] == 2 && d->hasVector == true, "document and marker written");
+    store.put_with_vector("c", "x", doc("x", 3, false), VectorChange::remove());
+    check(!store.get_vector("c", "x"), "remove drops the vector");
+    d = store.get("c", "x");
+    check(d && d->hasVector == false, "marker false after remove");
+    // Keep leaves the vector alone
+    store.put_with_vector("c", "y", doc("y", 1, true), VectorChange::put({1.f, 1.f}));
+    store.put_with_vector("c", "y", doc("y", 2, true), VectorChange::keep());
+    v = store.get_vector("c", "y");
+    check(v && *v == std::vector<float>{1.f, 1.f}, "keep leaves the vector in place");
+}
+
+void test_order_resume_and_stop() {
+    TmpEnv t("resume");
+    LmdbDocumentStore store(t.env);
+    for (int i = 0; i < 50; ++i) {
+        char id[8];
+        std::snprintf(id, sizeof id, "r%03d", i);
+        store.put("c", id, doc(id, i, false));
+    }
+    uint64_t count = 0;
+    auto all = scan(store, "", false, &count);
+    check(count == 50 && all.size() == 50, "50 rows, counted and offered");
+    bool ordered = true;
+    for (size_t i = 1; i < all.size(); ++i) ordered = ordered && all[i - 1].id < all[i].id;
+    check(ordered, "rows arrive in id order");
+
+    auto first = scan(store, "", false, nullptr, 20);
+    check(first.size() == 20 && first.back().id == "r019", "stopping after 20 stops at r019");
+    uint64_t rest = 0;
+    auto second = scan(store, first.back().id, false, &rest);
+    check(rest == 30 && second.size() == 30, "resume counts and offers the 30 after the cursor");
+    check(!second.empty() && second.front().id == "r020", "resume starts strictly after the cursor");
+
+    // A cursor that is not an existing id resumes at the next id after it.
+    auto between = scan(store, "r0195", false);
+    check(!between.empty() && between.front().id == "r020", "a cursor between ids resumes after it");
+    // A cursor past the end yields nothing.
+    uint64_t none = 99;
+    auto past = scan(store, "zzz", false, &none);
+    check(past.empty() && none == 0, "a cursor past the end: count 0, no rows");
+
+    // The predicate is applied to the count too.
+    uint64_t even = 0;
+    auto evens = scan(store, "", false, &even, 0,
+                      [](const Document& d) { return d.data()["n"].get<int>() % 2 == 0; });
+    check(even == 25 && evens.size() == 25, "a row predicate filters the count and the rows alike");
+}
+
+void test_missing_collection() {
+    TmpEnv t("missing");
+    LmdbDocumentStore store(t.env);
+    bool started = false;
+    const bool found = store.export_scan(
+        "nope", "", false, {}, [&](uint64_t) { started = true; },
+        [&](Document&&, VS, const float*, size_t) { return true; });
+    check(!found && !started, "a missing collection reports not found and starts nothing");
+}
+
+void test_marker_survives_json_roundtrip() {
+    // WAL and snapshot persist a Document through toJson/fromJson.
+    for (std::optional<bool> h : {std::optional<bool>{}, std::optional<bool>{true},
+                                  std::optional<bool>{false}}) {
+        Document d = doc("j", 1, h);
+        Document back = Document::fromJson(d.toJson());
+        check(back.hasVector == h, "hasVector survives toJson/fromJson");
+    }
+    check(!doc("j", 1, std::nullopt).toJson().contains("hasVector"),
+          "no marker is written when there is none");
+}
+
+void test_put_with_vector_is_one_commit() {
+    // A writer stores documents WITH vectors while a reader exports. Every
+    // row any snapshot sees must have its vector. With the document and the
+    // vector in two commits (pre-2.13.0) a snapshot between them sees the row
+    // marked as having a vector and no entry: a false MISSING, which looks
+    // exactly like real data loss. No MemoryStore lock here, unlike the e2e,
+    // so the reader can land in that gap.
+    TmpEnv t("atomic");
+    LmdbDocumentStore store(t.env);
+    std::atomic<bool> done{false};
+    std::thread writer([&]() {
+        const std::vector<float> v{1.f, 2.f, 3.f, 4.f};
+        for (int i = 0; i < 4000; ++i) {
+            const std::string id = "a" + std::to_string(i);
+            store.put_with_vector("c", id, doc(id, i, true), VectorChange::put(v));
+        }
+        done = true;
+    });
+    int exports = 0, seen = 0, notPresent = 0;
+    while (!done.load()) {
+        try {
+            for (auto& r : scan(store, "", true)) {
+                ++seen;
+                if (r.state != VS::Present) ++notPresent;
+            }
+            ++exports;
+        } catch (const std::exception&) {
+            // the collection's first commit may not have happened yet
+        }
+    }
+    writer.join();
+    std::cout << "  atomicity: " << exports << " exports, " << seen << " rows seen\n";
+    check(exports >= 3, "several exports ran during the writes");
+    check(notPresent == 0, "no snapshot saw a row without its vector (" +
+          std::to_string(notPresent) + " did)");
+}
+
+}  // namespace
+
+int main() {
+    test_put_with_vector_is_one_commit();
+    test_vector_states();
+    test_put_with_vector_replaces_and_removes();
+    test_order_resume_and_stop();
+    test_missing_collection();
+    test_marker_survives_json_roundtrip();
+    std::cout << "test_export_scan: " << g_pass << " passed, " << g_fail << " failed\n";
+    return g_fail == 0 ? 0 : 1;
+}

Некоторые файлы не были показаны из-за большого количества измененных файлов