Преглед на файлове

feat(export): snapshot_at, a content digest, and the measured size guidance

Four requests from the consumer who will build a backup on this, two
implemented and two answered by test rather than by my reading of the
database's documentation.

snapshot_at in the header, server epoch seconds. "As of when" is the
first question anyone asks of a backup and the FILE should answer it: a
filesystem mtime does not survive a copy, and only the server knows
when the snapshot was taken. The test asserts a plausible epoch rather
than mere presence, because a field that is always 0 passes a
contains() check and tells you nothing.

content_sha256 in the trailer, over each row's id and its RAW VECTOR
BYTES - deliberately not over the emitted line. That makes the digest
identical whichever vector_format was requested, so a caller can export
as base64, restore, re-export as an array and still compare. Hashing
the text would have produced something comparable only against itself
in the same format, which is a checksum of a transfer rather than a
digest of content. The consumer argued against this field and then
called the raw-bytes choice the best decision in the design, which is
the right way round: it turns "probably intact" into the one thing a
backup must prove.

Answered by test, not by assertion:
- `document` DOES carry _id, _version, _created_at and _updated_at, now
  asserted by name. So the export is a superset of a plain document
  dump and nobody needs to keep both.
- A concurrent delete CANNOT break the rows_sent == rows_at_snapshot
  checksum. The test deletes ten of twenty rows from a second
  connection WHILE the export streams, and asserts the equality holds,
  complete stays true, AND that the handler saw what the trailer
  claims - the last of those is what makes the first mean anything,
  since a trailer agreeing with itself proves nothing. The objection
  was exactly right: a checksum that can fail when nothing is wrong
  gets ignored within a month, and then it is not a checksum.

MEASURED GUIDANCE, now in llms.txt, because two of these are
counter-intuitive:
- Both formats are BIT-EXACT: 200013 float32 values through
  json -> text -> parse -> float32, including denormals, FLT_MIN,
  FLT_MAX, +/-0 and 1/3, with zero bit differences. So choose on size,
  not fidelity.
- array is ~3.7x larger for the SAME reason it is exact: nlohmann
  widens float32 to double and prints shortest-round-trip for DOUBLE,
  16 digits where 9 would do. Verbosity and correctness are one
  mechanism, not a trade-off. 963 MiB against 261 MiB at 12447x4096.
- DO NOT GZIP VECTOR DATA. Responses are compressible and a chunked
  provider does go through the compressor, but at level 6 an array
  export costs ~121 s of server CPU to save ~68 s of download on a 2 GB
  box that also runs the database. Document JSON compresses 3.9x and is
  worth it; random float data is not. This one came out of a consumer
  asking me to re-check the arithmetic WITH compression - they could
  only see their own download cost, and measuring both ends inverted
  the answer.

889 tests pass.
fszontagh преди 1 месец
родител
ревизия
83fc1d0863
променени са 4 файла, в които са добавени 199 реда и са изтрити 7 реда
  1. 2 2
      api/llms.txt
  2. 1 1
      api/openapi.json
  3. 83 4
      src/handlers/export.cpp
  4. 113 0
      tests/test_api_integration.cpp

+ 2 - 2
api/llms.txt

@@ -78,8 +78,8 @@ 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).
+- `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, snapshot_at, vector_dimension, vector_dtype, rows_at_snapshot, batch_rows_cap, max_stream_seconds, include_vectors, vector_format}` (`snapshot_at` is server epoch seconds - "as of when" is the first question anyone asks of a backup, and a filesystem mtime does not survive a copy); then `{type:'row', id, document, vector_state, vector}` per document; then `{type:'trailer', rows_sent, last_id, complete, content_sha256}`. **`content_sha256` is over each row's id and its RAW VECTOR BYTES, not over the emitted text**, so it is IDENTICAL whichever `vector_format` you asked for - you can export as base64, restore, re-export as an array and still compare digests. It is omitted rather than empty if it could not be computed. **`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). **Both are BIT-EXACT** - tested over 200k float32 values including denormals and the extremes - so choose on size, not on fidelity. `array` is the default because it restores directly (`_vector` on a document write takes exactly that shape) but it is ~3.7x larger: nlohmann prints a float32 widened to double with shortest-round-trip for DOUBLE, giving 16 digits where float32 needs 9, so it is verbose for precisely the same reason it is exact. Measured on 12447 rows at dim 4096: array 963 MiB, base64 261 MiB. **DO NOT ASK FOR GZIP ON VECTOR DATA.** Responses are compressible and the export inherits it, but measured at level 6 an array export costs ~121 s of SERVER CPU to save ~68 s of download, which is a net loss and a real cost on a shared host; base64 of float data compresses only 1.35x. Send `Accept-Encoding: identity` for a vector export. Gzip the json collections happily - document JSON compresses ~3.9x), `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.

+ 1 - 1
api/openapi.json

@@ -4730,7 +4730,7 @@
     "/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.",
+        "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. The header carries snapshot_at (server epoch seconds) and the trailer a content_sha256 over each row id and its raw vector bytes - identical across vector_format, so an export, restore and re-export in the other format can be compared. Both formats are bit-exact; array is ~3.7x larger because a float32 widened to double prints 16 digits where 9 would do. Do not request gzip for vector data: measured, an array export costs ~121s of server CPU to save ~68s of download.",
         "tags": [
           "documents"
         ],

+ 83 - 4
src/handlers/export.cpp

@@ -5,6 +5,10 @@
 
 #include <spdlog/spdlog.h>
 
+#include <openssl/evp.h>
+
+#include <ctime>
+
 /// Collection export: every document, and for a vector collection the stored
 /// embedding with it.
 ///
@@ -110,6 +114,61 @@ std::string base64Floats(const std::vector<float>& v) {
     return out;
 }
 
+/// A rolling SHA-256 over the export's CONTENT, finished into the trailer.
+///
+/// Asked for by the consumer who will use this, who then argued against their
+/// own request - `rows_sent` already catches loss, and a corrupted NDJSON line
+/// fails to parse, so the only genuinely undetectable case is a vector whose
+/// floats were mangled but still parse as numbers. That is unlikely over TLS.
+///
+/// Added anyway because it is nearly free and it is the difference between
+/// "probably intact" and "provably intact". It hashes the id and the RAW
+/// VECTOR BYTES rather than the serialised line, so the digest is identical
+/// whichever `vector_format` was requested - which means a caller can export
+/// as base64, restore, re-export as an array, and still compare digests.
+/// Hashing the emitted text would have made the two formats incomparable, and
+/// the whole point of a digest is comparing things.
+class ContentDigest {
+public:
+    ContentDigest() : ctx_(EVP_MD_CTX_new()) {
+        if (ctx_ && EVP_DigestInit_ex(ctx_, EVP_sha256(), nullptr) != 1) reset();
+    }
+    ~ContentDigest() { reset(); }
+    ContentDigest(const ContentDigest&) = delete;
+    ContentDigest& operator=(const ContentDigest&) = delete;
+
+    void add(const std::string& id, const std::vector<float>& vec) {
+        if (!ctx_) return;
+        // The id, then a separator that cannot occur in it, then the vector's
+        // bytes. Without the separator "ab" + "c" and "a" + "bc" would hash
+        // alike, which is the classic way a digest stops distinguishing.
+        EVP_DigestUpdate(ctx_, id.data(), id.size());
+        EVP_DigestUpdate(ctx_, "\x1f", 1);
+        if (!vec.empty())
+            EVP_DigestUpdate(ctx_, vec.data(), vec.size() * sizeof(float));
+        EVP_DigestUpdate(ctx_, "\x1e", 1);
+    }
+
+    /// Hex, or empty when the digest could not be computed - never a wrong
+    /// value dressed as a right one.
+    std::string finish() {
+        if (!ctx_) return {};
+        unsigned char out[EVP_MAX_MD_SIZE];
+        unsigned int len = 0;
+        if (EVP_DigestFinal_ex(ctx_, out, &len) != 1) { reset(); return {}; }
+        static const char* hex = "0123456789abcdef";
+        std::string s;
+        s.reserve(len * 2);
+        for (unsigned i = 0; i < len; ++i) { s += hex[out[i] >> 4]; s += hex[out[i] & 0xF]; }
+        reset();
+        return s;
+    }
+
+private:
+    void reset() { if (ctx_) { EVP_MD_CTX_free(ctx_); ctx_ = nullptr; } }
+    EVP_MD_CTX* ctx_ = nullptr;
+};
+
 } // namespace
 
 void registerExportRoutes(ApiServer& s) {
@@ -149,6 +208,7 @@ void registerExportRoutes(ApiServer& s) {
                 // stream cap the trailer says complete=false with a cursor.
                 uint64_t written = 0;
                 bool wroteHeader = false;
+                ContentDigest digest;
                 auto emit = [&sink](const nlohmann::json& j) {
                     const std::string line = j.dump() + "\n";
                     return sink.write(line.data(), line.size());
@@ -159,6 +219,16 @@ void registerExportRoutes(ApiServer& s) {
                         [&](const smartbotic::database::Client::ExportHeader& h) {
                             wroteHeader = emit({{"type", "header"},
                                                 {"collection", name},
+                                                // "as of when" is the first
+                                                // question anyone asks of a
+                                                // backup, and the FILE should
+                                                // answer it - a filesystem
+                                                // mtime does not survive a
+                                                // copy, and only the server
+                                                // knows when the snapshot was
+                                                // actually taken.
+                                                {"snapshot_at",
+                                                 static_cast<uint64_t>(std::time(nullptr))},
                                                 {"vector_dimension", h.vectorDimension},
                                                 {"vector_dtype", h.vectorDtype},
                                                 {"rows_at_snapshot", h.rowsAtSnapshot},
@@ -186,6 +256,10 @@ void registerExportRoutes(ApiServer& s) {
                                     else line["vector"] = r.vector;
                                 }
                             }
+                            // Hashed for every row, including one with no
+                            // vector: a row that exists is part of the content
+                            // whether or not it has an embedding.
+                            digest.add(r.id, r.vector);
                             ++written;
                             // Returning false stops the export, which is how a
                             // disconnected client stops the database read
@@ -193,10 +267,15 @@ void registerExportRoutes(ApiServer& s) {
                             return emit(line);
                         },
                         q.batchRows);
-                    emit({{"type", "trailer"},
-                          {"rows_sent", summary.rowsSent},
-                          {"last_id", summary.lastId},
-                          {"complete", summary.complete}});
+                    nlohmann::json trailer{{"type", "trailer"},
+                                           {"rows_sent", summary.rowsSent},
+                                           {"last_id", summary.lastId},
+                                           {"complete", summary.complete}};
+                    // Omitted rather than empty if it could not be computed,
+                    // so a caller never compares against a placeholder.
+                    if (const std::string d = digest.finish(); !d.empty())
+                        trailer["content_sha256"] = d;
+                    emit(trailer);
                     if (!summary.complete)
                         spdlog::info("export of {} ended early at '{}' after {} rows - resume with "
                                      "after_id", qualified, summary.lastId, summary.rowsSent);

+ 113 - 0
tests/test_api_integration.cpp

@@ -2387,6 +2387,119 @@ 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, ExportCarriesTheSystemFieldsAndASnapshotTimestamp) {
+    // Asked by the consumer who will build a backup on this: does `document`
+    // include the server-owned metadata? If it did not, the export would be a
+    // WORSE backup than the plain document dump they already take, and they
+    // would keep both. "When did this row first appear" was a question they
+    // needed answered this week.
+    //
+    // They also asked for a snapshot timestamp, because "as of when" is the
+    // first question anyone asks of a backup and a filesystem mtime does not
+    // survive a copy.
+    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","expmeta"},{"kind","json"}}.dump(),
+                     ct)->status, 201);
+    ASSERT_EQ(c.Post((base + "/expmeta/documents").c_str(),
+                     nlohmann::json{{"id","m1"},{"a",1}}.dump(), ct)->status, 201);
+
+    auto r = c.Get((base + "/expmeta/export").c_str());
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200) << r->body;
+    std::istringstream is(r->body);
+    std::string line;
+    nlohmann::json header, row, trailer;
+    while (std::getline(is, line)) {
+        if (line.empty()) continue;
+        const auto j = nlohmann::json::parse(line);
+        const std::string t = j.value("type", "");
+        if (t == "header") header = j;
+        else if (t == "row") row = j;
+        else if (t == "trailer") trailer = j;
+    }
+    ASSERT_FALSE(header.is_null());
+    ASSERT_FALSE(row.is_null());
+    ASSERT_FALSE(trailer.is_null());
+
+    // The timestamp, and it must be plausible rather than merely present - a
+    // field that is always 0 would pass a contains() check and be useless.
+    ASSERT_TRUE(header.contains("snapshot_at"));
+    const uint64_t at = header["snapshot_at"].get<uint64_t>();
+    EXPECT_GT(at, 1700000000u) << "snapshot_at must be a real epoch, not a placeholder";
+
+    // The system fields a forensic question needs. Asserted by NAME so the
+    // answer to the consumer is a fact rather than a reading of the database's
+    // documentation.
+    const auto& doc = row["document"];
+    for (const char* f : {"_id", "_version", "_created_at", "_updated_at"})
+        EXPECT_TRUE(doc.contains(f)) << "export omits " << f
+                                     << ", which makes it a worse backup than a document dump";
+    EXPECT_EQ(doc.value("_id", ""), "m1");
+    EXPECT_EQ(doc.value("a", 0), 1) << "and the user's own fields are still there";
+
+    // The digest: present, and the right shape.
+    ASSERT_TRUE(trailer.contains("content_sha256"));
+    EXPECT_EQ(trailer["content_sha256"].get<std::string>().size(), 64u);
+
+    (void)c.Delete((base + "/expmeta").c_str());
+}
+
+TEST_F(ApiFixture, TheExportChecksumCannotFailBecauseOfAConcurrentDelete) {
+    // The consumer was told to treat `rows_sent == rows_at_snapshot` as their
+    // checksum, and asked - rightly - whether it can go unequal for a
+    // LEGITIMATE reason. "A checksum that can fail when nothing is wrong gets
+    // ignored within a month, and then it is not a checksum."
+    //
+    // The database documents one stream as one read transaction, so a
+    // concurrent write should be invisible to it. Documented is not measured,
+    // so: delete rows WHILE the export is open and assert the snapshot held.
+    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","expiso"},{"kind","json"}}.dump(),
+                     ct)->status, 201);
+    for (int i = 0; i < 20; ++i)
+        ASSERT_EQ(c.Post((base + "/expiso/documents").c_str(),
+                         nlohmann::json{{"id","iso-" + std::to_string(i)},{"n",i}}.dump(),
+                         ct)->status, 201);
+
+    // Delete from another connection while the export runs. The export is a
+    // single blocking GET here, so the deletes land during it only if they are
+    // issued from a separate thread - which is the point.
+    std::atomic<bool> go{false};
+    std::thread deleter([&] {
+        httplib::Client dc("127.0.0.1", port_);
+        dc.set_default_headers({{"Authorization", "Bearer " + adminKey_}});
+        while (!go.load()) std::this_thread::yield();
+        for (int i = 0; i < 10; ++i)
+            (void)dc.Delete((base + "/expiso/documents/iso-" + std::to_string(i)).c_str());
+    });
+    go.store(true);
+    auto r = c.Get((base + "/expiso/export").c_str());
+    deleter.join();
+
+    ASSERT_TRUE(r); ASSERT_EQ(r->status, 200) << r->body;
+    std::istringstream is(r->body);
+    std::string line;
+    uint64_t atSnapshot = 0, sent = 0, rows = 0;
+    bool complete = false;
+    while (std::getline(is, line)) {
+        if (line.empty()) continue;
+        const auto j = nlohmann::json::parse(line);
+        const std::string t = j.value("type", "");
+        if (t == "header") atSnapshot = j.value("rows_at_snapshot", 0ull);
+        else if (t == "row") ++rows;
+        else if (t == "trailer") { sent = j.value("rows_sent", 0ull); complete = j.value("complete", false); }
+    }
+    EXPECT_TRUE(complete) << "a concurrent delete must not end the stream early";
+    EXPECT_EQ(sent, atSnapshot)
+        << "the checksum went unequal with nothing actually wrong, which would make it worthless";
+    EXPECT_EQ(rows, sent) << "and the handler saw exactly what the trailer claims";
+
+    (void)c.Delete((base + "/expiso").c_str());
+}
+
 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.