ソースを参照

feat: stream a collection out as a restorable backup, vectors included

The half of a backup that could not be written until database 2.13.0.
Nothing before it returned a stored vector - get, find and
similaritySearch all omit it, because the database consumes the
embedding into its index - so an "export" built on the read routes
produced documents that restore as rows no search can find. A consumer
has had a documented hole in their backup where the embeddings should
be, and was told not to round-trip documents through this API meanwhile.

GET /api/v1/projects/{p}/collections/{c}/export, streamed NDJSON.

Shape decisions, each with a wrong alternative:

- NDJSON rather than a JSON array, because the LINE is the unit of
  recovery: a truncated download loses the last row instead of the
  file. An array has to be complete to parse at all, which would make a
  12447-row collection at dimension 4096 a single ~600 MB token.
- Vectors are a JSON array by DEFAULT even though base64 is under half
  the bytes, because an array restores directly - `_vector` on a
  document write takes exactly that, so an export replays line by line
  with no conversion. A format that halves the size but requires the
  consumer to write a decoder is the wrong default for a thing whose
  only purpose is being restorable. vector_format=base64 is there when
  size matters more.
- include_vectors defaults to ON for a vector collection. Off would
  make the one feature this route exists for opt-in, so the commonest
  call would quietly produce the same unusable backup being fixed.
- Everything refusable is refused BEFORE the stream starts. Once a 200
  is on the wire an error can only look like truncation, and a caller
  cannot tell a refused export from a half one.
- A mid-stream failure emits a final {"type":"error"} line rather than
  stopping. A stream that merely stops is indistinguishable from a
  complete one whose trailer was lost, and a backup tool has to tell
  those apart.
- A row whose vector_state is not `present` carries NO vector field,
  not an empty array, so a restorer cannot read "we do not have it" as
  "it is empty" - which is the entire reason VectorState exists.
- BOTH the list and read grants are required: list alone can already
  learn the ids and must not get the contents, read alone must not get
  an enumeration.

The push/pull mismatch is handled without a thread: exportCollection
calls us per row while httplib's sink is pulled, so the whole stream is
produced inside one provider invocation, writing each row as it arrives.
Nothing larger than a single row is ever held, and sink.write blocking
on the socket means a slow consumer slows the database read rather than
filling memory - at worst reaching the server's stream cap, which the
trailer then reports as complete=false with a cursor.

Three integration tests, asserting OUTCOMES. The round trip restores
through our own PUT route and then SEARCHES for every row, checking each
is its own nearest neighbour with byte-identical vectors - not that the
export emitted N lines. Distinct vectors on purpose: identical ones tie,
and "is it its own nearest neighbour" would prove nothing. 887 pass.
fszontagh 1 ヶ月 前
親
コミット
46a392ccee
7 ファイル変更、522 行追加、1 行削除
  1. 6 0
      api/llms.txt
  2. 94 1
      api/openapi.json
  3. 1 0
      src/CMakeLists.txt
  4. 226 0
      src/handlers/export.cpp
  5. 1 0
      src/server.cpp
  6. 2 0
      src/server.hpp
  7. 192 0
      tests/test_api_integration.cpp

+ 6 - 0
api/llms.txt

@@ -78,6 +78,12 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
   **Conditional writes: `?if_version=N`** on PUT and PATCH. The write applies only if the document is still at version `N`; otherwise **409** `version_conflict` with `error.details.expected_version` and, when it can be read, `error.details.current_version`. Read `_version` from a GET or from a `?filter=` listing, write with `?if_version=` that value, and retry from a fresh read on 409. `N` must be a positive integer (**422** `validation` otherwise; versions start at 1, so `if_version=0` is not "must not exist"). A conditional write never creates: `?if_version=` on an absent document is **404**, on PUT as well as PATCH. On PATCH it cannot be combined with `?ttl_seconds=` (**422** `conditional_unsupported`): the version-checked write has no expiry field, and silently dropping one of the two would be worse than refusing. It IS available on a `kind=vector` collection - a conditional PATCH is a server-side MERGE and preserves the stored embedding (measured). What is refused there is a whole-document **replace**: see `PUT` below.
 - `POST  /api/v1/projects/{project}/collections/{name}/documents/{id}/increment` `{field: n, ...}` (or `{data:{...}}`) - **Atomic increment.** Adds each number to the named field in ONE locked server-side read-modify-write, so concurrent increments cannot lose each other. Dotted keys address nested fields (`counts.sent`). Returns **200** `{id, values}` where `values` holds the NEW value of every field you named. An absent or null field counts as 0. Integer + integer stays an integer (overflow is refused); anything else becomes a double. A field holding a non-number is **422** `validation` and **nothing at all is applied** - the whole set applies or none of it does. Needs the `update` grant (it is a write, so a read-only scope gets **403**); it is a separate route rather than a flag on PATCH because `{"calls":1}` means "set calls to 1" on PATCH and "add 1 to calls" here.
+- `GET   /api/v1/projects/{project}/collections/{name}/export` - **Streaming backup, including stored vectors.** Answers **NDJSON** (`application/x-ndjson`): one JSON object per line, so the LINE is the unit of recovery and a truncated download loses the last row rather than the file. First line `{type:'header', collection, vector_dimension, vector_dtype, rows_at_snapshot, batch_rows_cap, max_stream_seconds, include_vectors, vector_format}`; then `{type:'row', id, document, vector_state, vector}` per document; then `{type:'trailer', rows_sent, last_id, complete}`. **`rows_sent == rows_at_snapshot` with `complete: true` is your checksum** - one uninterrupted call is an exact snapshot with no row skipped or repeated, in id order. Needs BOTH the `list` and `read` grants: `list` alone could already learn the ids and must not get the contents, and `read` alone must not get an enumeration.
+  **Params:** `include_vectors` (default **true** for a vector collection, and refused **422** `not_vector` on a json one), `vector_format` (`array` default, or `base64` for float32-little-endian - roughly half the bytes, but `array` restores directly because `_vector` on a document write takes exactly that), `after_id` (resume), `batch_rows` (clamped, never refused).
+  **`vector_state` is `present`, `none`, `missing` or `unknown`,** and a row that is not `present` carries NO `vector` field at all rather than an empty one - so a restorer cannot mistake "we do not have it" for "it is empty". **`missing` means the row HAD a vector and the entry is gone** (real data loss) and `unknown` means the row predates the database's marker, so neither should be restored as a plain document: re-embed from the source text instead, or you will store a row that reads back fine and can never be found by a search.
+  **To restore:** replay each row as `PUT .../documents/{id}` with `document` plus `_vector` set to `vector`. The restored row gets FRESH metadata (`_version` restarts at 1, `_created_at` is the restore time); the originals are still in the exported `document` if you need them as data.
+  **Resuming is skip-possible, never duplicate.** `complete: false` means the stream ended early - the server's `max_stream_seconds` cap, or your client disconnecting - and `last_id` is the cursor: call again with `after_id=<last_id>`. A resume starts a NEW snapshot strictly after that id, so it never repeats a row but can miss one inserted during the gap with an id sorting before the cursor. For an airtight copy take one uninterrupted stream.
+  **A failure mid-stream emits a final `{type:'error', code, message, rows_sent, complete:false}` line** instead of simply stopping, because a stream that stops looks identical to a complete one whose trailer was lost. Treat a stream with no `trailer` AND no `error` line as failed.
 
   **It requires the document to exist** (**404** otherwise) and never creates one: the starting document is yours to describe. The idiom for a counter that may not exist yet is: increment; on **404** `POST .../documents` the document under a fixed `id` with its starting values; on **409** `duplicate_values` (someone else just created it) increment again.
 - `DELETE /api/v1/projects/{project}/collections/{name}/documents/{id}` - Delete a document. Returns **409** `relation_restricted` (with `error.details.impacts`) if a restrict relation has children referencing it; see delete-impact below to preview this first.

+ 94 - 1
api/openapi.json

@@ -4726,6 +4726,99 @@
           }
         }
       }
+    },
+    "/api/v1/projects/{project}/collections/{name}/export": {
+      "get": {
+        "summary": "Stream a collection as NDJSON, including stored vectors",
+        "description": "A restorable backup. One JSON object per line (header, then a row per document, then a trailer), so the line is the unit of recovery and a truncated download loses the last row rather than the file. `rows_sent == rows_at_snapshot` with `complete: true` is the checksum: one uninterrupted call is an exact snapshot, in id order, with no row skipped or repeated. Requires BOTH the `list` and `read` grants. A row whose `vector_state` is not `present` carries no `vector` field at all, so a restorer cannot mistake an absent vector for an empty one; `missing` is real data loss and `unknown` predates the database's marker, and neither should be restored as a plain document. Restore by replaying each row as `PUT .../documents/{id}` with `_vector` set to `vector`. Resuming with `after_id` starts a new snapshot strictly after that id: never duplicates, but can miss a row inserted during the gap. A failure mid-stream emits a final `{\"type\":\"error\"}` line rather than stopping silently, because a stream that stops is indistinguishable from one whose trailer was lost.",
+        "tags": [
+          "documents"
+        ],
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "name",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "include_vectors",
+            "in": "query",
+            "required": false,
+            "description": "Default true for a vector collection; 422 not_vector on a json collection.",
+            "schema": {
+              "type": "boolean"
+            }
+          },
+          {
+            "name": "vector_format",
+            "in": "query",
+            "required": false,
+            "description": "`array` (default, restores directly into _vector) or `base64` (float32 little-endian, about half the bytes).",
+            "schema": {
+              "type": "string",
+              "enum": [
+                "array",
+                "base64"
+              ]
+            }
+          },
+          {
+            "name": "after_id",
+            "in": "query",
+            "required": false,
+            "description": "Resume cursor: the trailer's last_id from a stream that reported complete=false.",
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "batch_rows",
+            "in": "query",
+            "required": false,
+            "description": "Rows per batch; clamped by the server rather than refused.",
+            "schema": {
+              "type": "integer",
+              "minimum": 0
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "NDJSON stream: header, rows, trailer (or a final error line).",
+            "content": {
+              "application/x-ndjson": {
+                "schema": {
+                  "type": "string"
+                },
+                "example": "{\"type\":\"header\",\"collection\":\"kb_chunks\",\"vector_dimension\":4096,\"vector_dtype\":\"float32-le\",\"rows_at_snapshot\":12447,\"include_vectors\":true,\"vector_format\":\"array\"}\n{\"type\":\"row\",\"id\":\"abc\",\"document\":{\"text\":\"...\"},\"vector_state\":\"present\",\"vector\":[0.01,0.02]}\n{\"type\":\"trailer\",\"rows_sent\":12447,\"last_id\":\"zzz\",\"complete\":true}\n"
+              }
+            }
+          },
+          "401": {
+            "$ref": "#/components/responses/Unauthorized"
+          },
+          "403": {
+            "$ref": "#/components/responses/Forbidden"
+          },
+          "404": {
+            "$ref": "#/components/responses/NotFound"
+          },
+          "422": {
+            "$ref": "#/components/responses/Unprocessable"
+          }
+        }
+      }
     }
   }
-}
+}

+ 1 - 0
src/CMakeLists.txt

@@ -43,6 +43,7 @@ add_library(vectorapi_core STATIC
     handlers/project_settings.cpp
     handlers/project_secrets.cpp
     handlers/files.cpp
+    handlers/export.cpp
     handlers/relations.cpp
     handlers/functions.cpp
     handlers/function_dispatch.cpp

+ 226 - 0
src/handlers/export.cpp

@@ -0,0 +1,226 @@
+#include "db_errors.hpp"
+#include "errors.hpp"
+#include "json_http.hpp"
+#include "server.hpp"
+
+#include <spdlog/spdlog.h>
+
+/// Collection export: every document, and for a vector collection the stored
+/// embedding with it.
+///
+/// This is the half of a backup that could not be written until database
+/// 2.13.0. Nothing before it returned a stored vector - `get`, `find` and
+/// `similaritySearch` all omit it, because the database consumes the embedding
+/// into its index - so an "export" built on the read routes produced documents
+/// that re-import as rows no search can find. A consumer had a documented hole
+/// in their backup where the embeddings should be, and was told not to
+/// round-trip documents through this API in the meantime.
+///
+/// NDJSON, streamed. One JSON object per line, and the line is the unit of
+/// recovery: a truncated download loses the last line rather than the file. A
+/// single JSON array would have to be complete to parse at all, and would make
+/// a 12448-row collection at dimension 4096 one ~600 MB token.
+namespace svapi {
+namespace {
+
+/// What a caller may ask for, parsed and bounded before anything streams.
+struct ExportQuery {
+    bool includeVectors = true;
+    bool base64Vectors = false;
+    std::string afterId;
+    uint32_t batchRows = 0;   // 0 = the database's own default
+};
+
+ExportQuery parseExportQuery(const httplib::Request& req, const CollectionMeta& meta) {
+    ExportQuery q;
+    // Vectors default to ON for a vector collection and are impossible for a
+    // json one. Defaulting to OFF would make the one feature this route exists
+    // for opt-in, and the commonest call would silently produce the same
+    // unusable backup we are fixing.
+    q.includeVectors = (meta.kind == "vector");
+    if (req.has_param("include_vectors")) {
+        const std::string v = req.get_param_value("include_vectors");
+        if (v != "true" && v != "false")
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "include_vectors must be 'true' or 'false'");
+        q.includeVectors = (v == "true");
+        // Refused here rather than relayed from the database, so the message
+        // names the collection's kind instead of an internal index condition.
+        if (q.includeVectors && meta.kind != "vector")
+            throw ApiError(ErrCode::Unprocessable, "not_vector",
+                           "collection '" + meta.name + "' is a json collection and has no "
+                           "vectors to export; omit include_vectors or pass false");
+    }
+    if (req.has_param("vector_format")) {
+        const std::string f = req.get_param_value("vector_format");
+        if (f != "array" && f != "base64")
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "vector_format must be 'array' or 'base64'");
+        q.base64Vectors = (f == "base64");
+    }
+    if (req.has_param("after_id")) q.afterId = req.get_param_value("after_id");
+    if (req.has_param("batch_rows")) {
+        try {
+            q.batchRows = static_cast<uint32_t>(std::stoul(req.get_param_value("batch_rows")));
+        } catch (...) {
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "batch_rows must be a non-negative integer");
+        }
+    }
+    return q;
+}
+
+const char* stateName(smartbotic::database::Client::VectorState s) {
+    using V = smartbotic::database::Client::VectorState;
+    switch (s) {
+        case V::Present: return "present";
+        case V::None: return "none";
+        case V::Missing: return "missing";
+        case V::Unknown: return "unknown";
+        case V::Unspecified: break;
+    }
+    return "unspecified";
+}
+
+/// float32 little-endian, base64'd. Offered because a 4096-float vector is
+/// ~16 KB raw and ~50 KB as a JSON array, so an array export of a 12448-row
+/// collection is ~600 MB where base64 is ~280 MB.
+///
+/// `array` remains the DEFAULT despite that, because it restores directly: our
+/// own document write takes `_vector` as a JSON array, so an array export can
+/// be replayed line by line with no conversion step. A format that halves the
+/// size but requires the consumer to write a decoder is the wrong default for
+/// something whose entire purpose is being restorable.
+std::string base64Floats(const std::vector<float>& v) {
+    static const char* tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    const auto* p = reinterpret_cast<const unsigned char*>(v.data());
+    const size_t n = v.size() * sizeof(float);
+    std::string out;
+    out.reserve((n + 2) / 3 * 4);
+    for (size_t i = 0; i < n; i += 3) {
+        const unsigned a = p[i];
+        const unsigned b = (i + 1 < n) ? p[i + 1] : 0;
+        const unsigned c = (i + 2 < n) ? p[i + 2] : 0;
+        const unsigned t = (a << 16) | (b << 8) | c;
+        out += tbl[(t >> 18) & 0x3F];
+        out += tbl[(t >> 12) & 0x3F];
+        out += (i + 1 < n) ? tbl[(t >> 6) & 0x3F] : '=';
+        out += (i + 2 < n) ? tbl[t & 0x3F] : '=';
+    }
+    return out;
+}
+
+} // namespace
+
+void registerExportRoutes(ApiServer& s) {
+    auto& svr = s.raw();
+    ServerDeps* d = &s.deps();
+
+    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/export)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey key = requireKey(*d, req);
+        const std::string project = req.matches[1], name = req.matches[2];
+        // BOTH ops: this enumerates the collection AND returns every document
+        // body. A key granted only `list` can already learn the ids; it must
+        // not get the contents, and a key granted only `read` must not get an
+        // enumeration it was never given.
+        requireCapability(*d, key, req, project, name, KeyOp::List);
+        requireCapability(*d, key, req, project, name, KeyOp::Read);
+
+        auto meta = d->registry.get(project, name);
+        if (!meta) throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
+        const ExportQuery q = parseExportQuery(req, *meta);
+        const std::string qualified = qualify(project, name);
+
+        // Everything that can be refused has been refused by now, because once
+        // the chunked response starts the status line is already sent and an
+        // error can only be a truncated body. A caller cannot tell a refused
+        // export from a half one if the refusal arrives after the 200.
+        res.set_header("X-Export-Collection", name);
+        res.set_chunked_content_provider(
+            "application/x-ndjson",
+            [d, qualified, name, q](size_t /*offset*/, httplib::DataSink& sink) {
+                // The export is PUSH (it calls us per row) and the sink is
+                // PULL, so the whole stream is produced inside this single
+                // invocation: each row is written as it arrives and nothing
+                // larger than one row is ever held. sink.write blocks on the
+                // socket, so a slow consumer slows the database read rather
+                // than filling memory - and if that pushes past the server's
+                // stream cap the trailer says complete=false with a cursor.
+                uint64_t written = 0;
+                bool wroteHeader = false;
+                auto emit = [&sink](const nlohmann::json& j) {
+                    const std::string line = j.dump() + "\n";
+                    return sink.write(line.data(), line.size());
+                };
+                try {
+                    const auto summary = d->db.client().exportCollection(
+                        qualified, q.includeVectors, q.afterId,
+                        [&](const smartbotic::database::Client::ExportHeader& h) {
+                            wroteHeader = emit({{"type", "header"},
+                                                {"collection", name},
+                                                {"vector_dimension", h.vectorDimension},
+                                                {"vector_dtype", h.vectorDtype},
+                                                {"rows_at_snapshot", h.rowsAtSnapshot},
+                                                {"batch_rows_cap", h.batchRowsCap},
+                                                {"max_stream_seconds", h.maxStreamSeconds},
+                                                {"include_vectors", q.includeVectors},
+                                                {"vector_format",
+                                                 q.base64Vectors ? "base64" : "array"}});
+                        },
+                        [&](smartbotic::database::Client::ExportRow&& r) {
+                            nlohmann::json line{{"type", "row"},
+                                                {"id", r.id},
+                                                {"document", std::move(r.document)}};
+                            if (q.includeVectors) {
+                                line["vector_state"] = stateName(r.vectorState);
+                                // Only a PRESENT row carries one. A missing or
+                                // unknown state is reported WITHOUT a vector
+                                // rather than with an empty array, so a
+                                // restorer cannot mistake "we do not have it"
+                                // for "it is empty" - that confusion is the
+                                // whole reason VectorState exists.
+                                if (r.vectorState ==
+                                    smartbotic::database::Client::VectorState::Present) {
+                                    if (q.base64Vectors) line["vector_b64"] = base64Floats(r.vector);
+                                    else line["vector"] = r.vector;
+                                }
+                            }
+                            ++written;
+                            // Returning false stops the export, which is how a
+                            // disconnected client stops the database read
+                            // instead of us streaming into a dead socket.
+                            return emit(line);
+                        },
+                        q.batchRows);
+                    emit({{"type", "trailer"},
+                          {"rows_sent", summary.rowsSent},
+                          {"last_id", summary.lastId},
+                          {"complete", summary.complete}});
+                    if (!summary.complete)
+                        spdlog::info("export of {} ended early at '{}' after {} rows - resume with "
+                                     "after_id", qualified, summary.lastId, summary.rowsSent);
+                } catch (const smartbotic::database::Client::Error& e) {
+                    // The status line is long gone, so the only honest thing
+                    // left is a final line SAYING it failed. A stream that
+                    // simply stops looks identical to a complete one whose
+                    // trailer was lost, and a backup tool must be able to tell
+                    // those apart - which is why every export ends with either
+                    // a trailer or this.
+                    const ApiError mapped = apiErrorFor(e);
+                    spdlog::error("export of {} failed after {} rows: {}", qualified, written,
+                                  e.what());
+                    emit({{"type", "error"},
+                          {"code", mapped.slug},
+                          {"message", mapped.what()},
+                          {"rows_sent", written},
+                          {"complete", false}});
+                }
+                (void)wroteHeader;
+                sink.done();
+                return true;
+            });
+    });
+}
+
+} // namespace svapi

+ 1 - 0
src/server.cpp

@@ -186,6 +186,7 @@ void ApiServer::registerRoutes() {
     registerProjectSettingsRoutes(*this);
     registerProjectSecretRoutes(*this);
     registerFileRoutes(*this);
+    registerExportRoutes(*this);
     registerRelationRoutes(*this);
     registerFunctionRoutes(*this);
     // LAST. Function dispatch owns /fn/* , and registering it after the

+ 2 - 0
src/server.hpp

@@ -91,6 +91,8 @@ void registerSettingsRoutes(ApiServer&);
 void registerProjectSettingsRoutes(ApiServer&);
 void registerProjectSecretRoutes(ApiServer&);
 void registerFileRoutes(ApiServer&);
+/// Streaming NDJSON collection export, including stored vectors (database 2.13.0+).
+void registerExportRoutes(ApiServer&);
 void registerRelationRoutes(ApiServer&);
 void registerFunctionRoutes(ApiServer&);
 // Registered LAST: it claims /fn/* , and a function route must never shadow

+ 192 - 0
tests/test_api_integration.cpp

@@ -2387,6 +2387,198 @@ TEST_F(ApiFixture, ARecycledCollectionNameInheritsNoConstraint) {
 // the vector so a read-modify-write cannot put it back. Measured against the
 // database before fixing: a merge PATCH preserves the vector, an update drops
 // it. On data that cost money to produce.
+TEST_F(ApiFixture, ExportingAVectorCollectionRoundTripsThroughOurOwnApi) {
+    // The property that matters, and the only one worth asserting: a collection
+    // exported and replayed through our OWN write route comes back searchable.
+    //
+    // This is the half of a backup that was impossible before database 2.13.0 -
+    // no read returned a stored vector, so an "export" built on the read routes
+    // produced documents that restore as rows no search can find. A consumer
+    // has had a documented hole in their backup where the embeddings should be.
+    //
+    // So the test restores and SEARCHES. Asserting that the export contained N
+    // lines would be asserting a mechanism; asserting the restored row is found
+    // by a similarity search is asserting the outcome.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    const std::string ct = "application/json";
+
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","expsrc"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(), ct)->status, 201);
+    // Distinct vectors, so "is it its own nearest neighbour" is a meaningful
+    // question - identical vectors tie and the assertion would prove nothing.
+    const std::vector<std::vector<double>> vecs = {
+        {1.0, 0.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 0.0},
+        {0.0, 0.0, 1.0, 0.0}, {0.25, 0.5, 0.75, 1.0}};
+    std::vector<std::string> ids;
+    for (size_t i = 0; i < vecs.size(); ++i) {
+        auto r = c.Post((base + "/expsrc/vectors").c_str(),
+                        nlohmann::json{{"vector", vecs[i]},
+                                       {"metadata", {{"tag", "t" + std::to_string(i)}}}}.dump(), ct);
+        ASSERT_TRUE(r); ASSERT_EQ(r->status, 201) << r->body;
+        ids.push_back(nlohmann::json::parse(r->body).value("id", ""));
+        ASSERT_FALSE(ids.back().empty());
+    }
+    // One row deliberately WITHOUT a vector, written through the documents
+    // route before 0.8.3 would have refused it - so instead, prove the export
+    // reports a json-collection row faithfully. Here we simply check the vector
+    // collection's own states.
+
+    // --- the export ------------------------------------------------------
+    auto exp = c.Get((base + "/expsrc/export").c_str());
+    ASSERT_TRUE(exp);
+    ASSERT_EQ(exp->status, 200) << exp->body;
+    EXPECT_NE(exp->get_header_value("Content-Type").find("ndjson"), std::string::npos);
+
+    // Parse NDJSON: one object per line, which is the unit of recovery.
+    std::vector<nlohmann::json> lines;
+    {
+        std::istringstream is(exp->body);
+        std::string line;
+        while (std::getline(is, line)) if (!line.empty()) lines.push_back(nlohmann::json::parse(line));
+    }
+    ASSERT_GE(lines.size(), vecs.size() + 2u) << "header + rows + trailer";
+    EXPECT_EQ(lines.front().value("type", ""), "header");
+    EXPECT_EQ(lines.front().value("vector_dimension", 0), 4);
+    EXPECT_EQ(lines.front().value("include_vectors", false), true);
+    EXPECT_EQ(lines.front().value("vector_format", ""), "array");
+    EXPECT_EQ(lines.back().value("type", ""), "trailer");
+    EXPECT_EQ(lines.back().value("complete", false), true)
+        << "an uninterrupted export must say so, or a half one is indistinguishable";
+    EXPECT_EQ(lines.back().value("rows_sent", 0u), vecs.size());
+
+    // Every row carries its id, its state, and a vector of the right width.
+    size_t present = 0;
+    std::map<std::string, std::vector<double>> exported;
+    for (const auto& l : lines) {
+        if (l.value("type", "") != "row") continue;
+        ASSERT_FALSE(l.value("id", "").empty()) << "a row without an id cannot be restored";
+        EXPECT_EQ(l.value("vector_state", ""), "present");
+        ASSERT_TRUE(l.contains("vector"));
+        ASSERT_EQ(l["vector"].size(), 4u);
+        exported[l["id"]] = l["vector"].get<std::vector<double>>();
+        ++present;
+    }
+    EXPECT_EQ(present, vecs.size());
+
+    // --- the restore, through our OWN document write ---------------------
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","expdst"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(), ct)->status, 201);
+    for (const auto& l : lines) {
+        if (l.value("type", "") != "row") continue;
+        nlohmann::json doc = l["document"];
+        doc["_vector"] = l["vector"];          // exactly what the docs tell a caller to do
+        auto put = c.Put((base + "/expdst/documents/" + l.value("id", "")).c_str(), doc.dump(), ct);
+        ASSERT_TRUE(put);
+        EXPECT_EQ(put->status, 201) << put->body;
+    }
+
+    // --- the assertion that matters: searchable again --------------------
+    for (size_t i = 0; i < vecs.size(); ++i) {
+        auto r = c.Post((base + "/expdst/search").c_str(),
+                        nlohmann::json{{"query_vector", vecs[i]},{"top_k",1}}.dump(), ct);
+        ASSERT_TRUE(r); ASSERT_EQ(r->status, 200) << r->body;
+        const auto hits = nlohmann::json::parse(r->body)["results"];
+        ASSERT_EQ(hits.size(), 1u) << "a restored row must be findable, which is the whole point";
+        EXPECT_EQ(hits[0].value("id", ""), ids[i])
+            << "the restored row must be its OWN nearest neighbour";
+    }
+
+    // And the vectors came back byte-for-byte, not merely close.
+    auto exp2 = c.Get((base + "/expdst/export").c_str());
+    ASSERT_TRUE(exp2); ASSERT_EQ(exp2->status, 200);
+    std::istringstream is2(exp2->body);
+    std::string l2;
+    size_t compared = 0;
+    while (std::getline(is2, l2)) {
+        if (l2.empty()) continue;
+        const auto j = nlohmann::json::parse(l2);
+        if (j.value("type", "") != "row") continue;
+        const auto it = exported.find(j.value("id", ""));
+        ASSERT_NE(it, exported.end());
+        EXPECT_EQ(j["vector"].get<std::vector<double>>(), it->second)
+            << "a restored vector must be identical, not approximate";
+        ++compared;
+    }
+    EXPECT_EQ(compared, vecs.size());
+
+    (void)c.Delete((base + "/expsrc").c_str());
+    (void)c.Delete((base + "/expdst").c_str());
+}
+
+TEST_F(ApiFixture, ExportRefusesVectorsFromAJsonCollectionAndSaysWhy) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    const std::string ct = "application/json";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","expjson"},{"kind","json"}}.dump(), ct)->status, 201);
+    ASSERT_EQ(c.Post((base + "/expjson/documents").c_str(),
+                     nlohmann::json{{"a",1}}.dump(), ct)->status, 201);
+
+    // Asking for vectors from a collection that cannot have them is a caller
+    // mistake worth naming, and it must be refused BEFORE the stream starts -
+    // once a 200 is on the wire a refusal can only look like truncation.
+    auto bad = c.Get((base + "/expjson/export?include_vectors=true").c_str());
+    ASSERT_TRUE(bad);
+    EXPECT_EQ(bad->status, 422) << bad->body;
+    EXPECT_NE(bad->body.find("not_vector"), std::string::npos) << bad->body;
+
+    // Without the flag it exports happily, with vectors off by default.
+    auto ok = c.Get((base + "/expjson/export").c_str());
+    ASSERT_TRUE(ok);
+    ASSERT_EQ(ok->status, 200) << ok->body;
+    std::istringstream is(ok->body);
+    std::string line;
+    ASSERT_TRUE(std::getline(is, line));
+    const auto header = nlohmann::json::parse(line);
+    EXPECT_EQ(header.value("include_vectors", true), false);
+    EXPECT_EQ(header.value("vector_dimension", -1), 0);
+
+    (void)c.Delete((base + "/expjson").c_str());
+}
+
+TEST_F(ApiFixture, ExportResumesFromACursorWithoutRepeatingARow) {
+    // A backup tool resumes; the trailer's last_id is how. Asserting it never
+    // repeats matters more than asserting it continues, because a duplicate on
+    // restore is silent where a gap is at least countable.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    const std::string ct = "application/json";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","expres"},{"kind","json"}}.dump(), ct)->status, 201);
+    for (int i = 0; i < 12; ++i)
+        ASSERT_EQ(c.Post((base + "/expres/documents").c_str(),
+                         nlohmann::json{{"id","row-" + std::to_string(i)},{"n",i}}.dump(),
+                         ct)->status, 201);
+
+    auto idsOf = [&](const std::string& url) {
+        std::set<std::string> out;
+        auto r = c.Get(url.c_str());
+        EXPECT_TRUE(r); if (!r) return out;
+        EXPECT_EQ(r->status, 200) << r->body;
+        std::istringstream is(r->body);
+        std::string line;
+        while (std::getline(is, line)) {
+            if (line.empty()) continue;
+            const auto j = nlohmann::json::parse(line);
+            if (j.value("type", "") == "row") out.insert(j.value("id", ""));
+        }
+        return out;
+    };
+    const auto all = idsOf(base + "/expres/export");
+    ASSERT_EQ(all.size(), 12u);
+
+    // Resume from the sixth id: everything after it, and nothing at or before.
+    const auto after = idsOf(base + "/expres/export?after_id=row-5");
+    EXPECT_EQ(after.count("row-5"), 0u) << "the cursor row itself must not repeat";
+    EXPECT_FALSE(after.empty());
+    for (const auto& id : after) EXPECT_GT(id, "row-5") << "resumed ids must be strictly after";
+
+    (void)c.Delete((base + "/expres").c_str());
+}
+
 TEST_F(ApiFixture, InsertingAVectorlessDocumentIntoAVectorCollectionIsRefused) {
     // The sibling of the PUT refusal below, through a different door. Reported
     // from production with the only symptom it has: a 12448-document collection