ソースを参照

feat: 2.19.0 - a document's expiry can be read: _expires_at

Asked by smartbotic-vectorapi after a consumer's incident: a TTL could be
written and never read back, so a backup compared with live looked like data
loss (an expired marker the sweep had reaped) and a restore made expired rows
permanent. The server always sent Document.expires_at; the client dropped it.
get/find/export now attach _expires_at (absolute ms) when set; it is
filterable (0 = absent, so an upper bound never matches a non-expiring row;
capability document_expires_at) and reserved in write bodies, stripped by the
server and by the client (for older servers). Tests: test_document_expiry
(18; reverted: read 4, filters 4, strip 2). ABI: one constexpr, soname 2.
fszontagh 1 ヶ月 前
親
コミット
a55c9b7542

ファイルの差分が大きいため隠しています
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.18.1
+2.19.0

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

@@ -337,6 +337,11 @@ public:
         /// string-to-string; null, booleans and type mismatches never match.
         /// Older servers compared across JSON types (null < bool < number < string).
         static constexpr const char* kTypedRangeFilters = "typed_range_filters";
+        /// 2.19.0: `_expires_at` (absolute expiry, ms since epoch) can be
+        /// filtered on, and is never stored from a write body. READING it needs
+        /// no capability: every server sends it, and this client attaches it
+        /// to get/find/export results when a document has an expiry.
+        static constexpr const char* kDocumentExpiresAt = "document_expires_at";
     };
 
     struct ServerInfo {

+ 25 - 4
client/src/client.cpp

@@ -205,6 +205,19 @@ 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.
+// v2.19.0 - the JSON text of a write body, without `_expires_at`: reads attach
+// it, so a get-then-write round trip would otherwise send it back, and a server
+// older than 2.19.0 would store it as an ordinary field (the 2.13.0 shadow-
+// field defect for the other metadata names). Copies only when present.
+std::string writeBodyText(const nlohmann::json& body) {
+    if (body.is_object() && body.contains("_expires_at")) {
+        nlohmann::json copy = body;
+        copy.erase("_expires_at");
+        return copy.dump();
+    }
+    return body.dump();
+}
+
 nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) {
     auto json = nlohmann::json::parse(doc.data());
     json["_id"] = doc.id();
@@ -213,6 +226,13 @@ nlohmann::json documentToJson(const smartbotic::databasepb::Document& doc) {
     json["_updated_at"] = doc.updated_at();
     json["_created_by"] = doc.created_by();
     json["_updated_by"] = doc.updated_by();
+    // v2.19.0 - the absolute expiry, milliseconds since the epoch, present only
+    // when the document has one. Every server has always sent it
+    // (Document.expires_at); the client dropped it, so a TTL could be written
+    // and never read back - and a backup restored without it made an expired
+    // row permanent. It may lie in the PAST: expiry is reaped by a periodic
+    // sweep, and a `restrict` relation can hold a row beyond it.
+    if (doc.expires_at() != 0) json["_expires_at"] = doc.expires_at();
     if (!doc.vector().empty()) {
         if (doc.vector().size() % sizeof(float) != 0) {
             throw DetailedError(Client::ErrorCode::DataLoss,
@@ -482,7 +502,7 @@ public:
                       const std::string& actor) {
         smartbotic::databasepb::InsertRequest request;
         request.set_collection(qualify(collection));
-        request.set_data(data.dump());
+        request.set_data(writeBodyText(data));
         if (!id.empty()) {
             request.set_id(id);
         }
@@ -567,6 +587,7 @@ public:
         cleanData.erase("_updated_at");
         cleanData.erase("_created_by");
         cleanData.erase("_updated_by");
+        cleanData.erase("_expires_at");
 
         // Optimistic locking with automatic retry:
         // 1. Read current version
@@ -643,7 +664,7 @@ public:
         smartbotic::databasepb::UpdateRequest request;
         request.set_collection(qualify(collection));
         request.set_id(id);
-        request.set_data(data.dump());
+        request.set_data(writeBodyText(data));
         request.set_expected_version(expectedVersion);
         if (!actor.empty()) {
             request.set_actor(actor);
@@ -702,7 +723,7 @@ public:
         request.set_id(id);
         // v2.12.0 - an increment-only call sends no merge patch.
         if (!(increments != nullptr && fields.is_object() && fields.empty())) {
-            request.set_patch_json(fields.dump());
+            request.set_patch_json(writeBodyText(fields));
         }
         if (expectedVersion.has_value()) request.set_expected_version(*expectedVersion);
         if (increments != nullptr) request.set_increments_json(increments->dump());
@@ -758,7 +779,7 @@ public:
                                         const std::string& actor) {
         smartbotic::databasepb::UpsertRequest request;
         request.set_collection(qualify(collection));
-        request.set_data(data.dump());
+        request.set_data(writeBodyText(data));
         if (!id.empty()) {
             request.set_id(id);
         }

+ 4 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.18.1** (client side; server 2.18.0) (see `VERSION`). Last reviewed: 2026-10-13.
+**Released version: 2.19.0** (see `VERSION`). Last reviewed: 2026-10-13.
 
 > 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.18.0. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.19.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -72,6 +72,8 @@ detail and the failure modes.
   vectors accepted in encrypted collections (2.17.2)
 - Typed range filters: GT/GTE/LT/LTE match number~number and string~string
   only, scan and index alike (2.18.0)
+- A document's expiry is readable (`_expires_at` on get/find/export),
+  filterable, and reserved in write bodies (2.19.0)
 - Optional per-collection JSON Schema (enforce/audit, existing rows checked
   first, suggested from data) (2.16.0)
 - Independent client and server releases: `GetServerInfo` capability

+ 32 - 1
docs/integration-guide.md

@@ -804,10 +804,41 @@ store every read uses. `dropCollection` still accepts such a name, so leftovers
 can be removed. A bare `_name` is not qualified by the client and lives in the
 global namespace (the system collections); that is unchanged.
 
+### Reading a document's expiry: `_expires_at` (2.19.0+)
+
+A document written with a TTL (`insert`/`upsert` `ttlSeconds`, `patchWithTtl`,
+or the collection's `defaultTtlSeconds`) now reads back with **`_expires_at`**:
+its absolute expiry, milliseconds since the epoch, beside `_version` and the
+other metadata. A document without an expiry has no `_expires_at` at all.
+
+- **get, find and exportCollection all carry it** - the server has always sent
+  it, the client used to drop it. A 2.19.0 client reads it from any server.
+- **It may lie in the past.** Expiry is applied by a sweep (every second on a
+  running server), and a `restrict` relation can deliberately hold a row past
+  its TTL. A copy of the data directory taken while the server was stopped
+  keeps expired rows until the next server that opens it sweeps them - which is
+  how a backup can hold a row "121 hours past its deadline" that the live
+  database no longer has. Compare `_expires_at` with the clock before
+  concluding a row was lost.
+- **Restoring:** a restore must carry the expiry, or an expired row comes back
+  PERMANENT (for an idempotency marker that suppresses the work it guards
+  forever). For each exported row: if `_expires_at` is absent, insert without a
+  TTL; if it is in the past, SKIP the row; otherwise insert with
+  `ttlSeconds = ceil((_expires_at - now) / 1000)`.
+- **Filterable** on a 2.19.0+ server (capability `document_expires_at`):
+  `Filter::lt("_expires_at", t)` finds what expires before `t`;
+  `Filter::exists("_expires_at", false)` finds documents that never expire. A
+  document without an expiry is ABSENT for these filters (never "0"), so an
+  upper bound does not match it. Not available as a sort key.
+- **Never stored from a write body** - it is a reserved name (below). A read
+  document written back keeps or loses its expiry only through the TTL
+  arguments, never through this field. Against a server older than 2.19.0 the
+  2.19.0 client strips it itself, so a round trip cannot store it there either.
+
 ### 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
+(and, since 2.19.0, `_expires_at`) 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

+ 2 - 1
service/src/document.hpp

@@ -23,7 +23,8 @@ namespace smartbotic::database {
  */
 inline bool isReservedField(std::string_view key) {
     return key == "_id" || key == "_version" || key == "_created_at" ||
-           key == "_updated_at" || key == "_created_by" || key == "_updated_by";
+           key == "_updated_at" || key == "_created_by" || key == "_updated_by" ||
+           key == "_expires_at";   // v2.19.0: reads attach it; a write never stores it
 }
 
 /** Remove the reserved metadata names from a top-level write body. */

+ 2 - 1
service/src/server_capabilities.hpp

@@ -18,7 +18,7 @@
 
 namespace smartbotic::database {
 
-inline constexpr std::array<std::string_view, 24> kServerCapabilities = {
+inline constexpr std::array<std::string_view, 25> kServerCapabilities = {
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "access_policy",         // 2.7.0  row/column security
     "query_projection",      // 2.7.1  FindRequest.projection
@@ -43,6 +43,7 @@ inline constexpr std::array<std::string_view, 24> kServerCapabilities = {
     "collection_schema",     // 2.16.0 Set/Get/SuggestCollectionSchema, schema_violation
     "encryption_at_rest",    // 2.17.0 encrypted collections encrypt, VerifyEncryption, encrypted_field
     "typed_range_filters",   // 2.18.0 GT/GTE/LT/LTE match number~number and string~string only
+    "document_expires_at",   // 2.19.0 _expires_at filterable; reserved in write bodies
 };
 
 }  // namespace smartbotic::database

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

@@ -172,6 +172,12 @@ std::optional<nlohmann::json> resolve_from_yyjson(yyjson_val* root,
     if (field == "_created_at") return to_json(yyjson_obj_get(root, "createdAt"));
     if (field == "_updated_at") return to_json(yyjson_obj_get(root, "updatedAt"));
     if (field == "_version")    return to_json(yyjson_obj_get(root, "version"));
+    // v2.19.0 - as filter_eval::resolveFilterValue: 0 (no expiry) is absent.
+    if (field == "_expires_at") {
+        yyjson_val* e = yyjson_obj_get(root, "expiresAt");
+        if (!e || !yyjson_is_uint(e) || yyjson_get_uint(e) == 0) return std::nullopt;
+        return to_json(e);
+    }
 
     yyjson_val* data = yyjson_obj_get(root, "data");
     if (!data) return std::nullopt;

+ 7 - 0
service/src/storage/filter_eval.hpp

@@ -136,6 +136,13 @@ resolveFilterValue(const smartbotic::database::Document& doc,
     if (field == "_updated_at") return nlohmann::json(doc.updatedAt);
     if (field == "_id")         return nlohmann::json(doc.id);
     if (field == "_version")    return nlohmann::json(doc.version);
+    // v2.19.0 - the absolute expiry (ms since epoch). 0 is stored for "no
+    // expiry" and resolves to ABSENT, so `_expires_at < X` never matches a
+    // document that does not expire.
+    if (field == "_expires_at") {
+        return doc.expiresAt ? std::optional<nlohmann::json>(nlohmann::json(doc.expiresAt))
+                             : std::nullopt;
+    }
     if (field.find('.') == std::string::npos) {
         return doc.field(field);
     }

+ 112 - 0
tests/load_test/test_document_expiry.cpp

@@ -0,0 +1,112 @@
+// v2.19.0 - a document's expiry can be READ: get/find/export attach
+// `_expires_at` (absolute, ms since the epoch) when the document has one, it can
+// be filtered on, and a write body never stores it. Before, a TTL could be
+// written (insert/upsert ttl, patchWithTtl) and never read back, so a restore
+// from a backup or export could not carry it and made expired rows permanent
+// (reported by smartbotic-vectorapi after an incident).
+
+#include <smartbotic/database/client.hpp>
+
+#include <chrono>
+#include <cstdlib>
+#include <iostream>
+#include <set>
+#include <string>
+#include <thread>
+
+using namespace smartbotic::database;
+using F = Client::Filter;
+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 int64_t nowMs() {
+    return std::chrono::duration_cast<std::chrono::milliseconds>(
+        std::chrono::system_clock::now().time_since_epoch()).count();
+}
+static bool near(const nlohmann::json& d, int64_t expect, int64_t slackMs) {
+    if (!d.contains("_expires_at") || !d["_expires_at"].is_number()) return false;
+    return std::llabs(d["_expires_at"].get<int64_t>() - expect) <= slackMs;
+}
+static std::set<std::string> ids(Client& c, const std::string& coll, std::vector<F> f) {
+    Client::QueryOptions o;
+    o.filters = std::move(f);
+    std::set<std::string> out;
+    for (auto& d : c.find(coll, o)) out.insert(d["_id"].get<std::string>());
+    return out;
+}
+
+int main() {
+    Client::Config cfg;
+    cfg.address = "127.0.0.1:9035";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+    ck(c.serverSupports(Client::Capability::kDocumentExpiresAt), "server reports document_expires_at");
+
+    const int64_t t0 = nowMs();
+    c.insert("exp", {{"name", "marker"}}, "t1", 3600);
+    c.insert("exp", {{"name", "forever"}}, "n1");
+
+    auto t1 = c.get("exp", "t1");
+    ck(t1 && near(*t1, t0 + 3600000, 60000), "get: _expires_at is now + 3600 s");
+    auto n1 = c.get("exp", "n1");
+    ck(n1 && !n1->contains("_expires_at"), "get: no _expires_at on a document without expiry");
+    {
+        Client::QueryOptions o;
+        bool t1Has = false, n1Has = true;
+        for (auto& d : c.find("exp", o)) {
+            if (d["_id"] == "t1") t1Has = near(d, t0 + 3600000, 60000);
+            if (d["_id"] == "n1") n1Has = d.contains("_expires_at");
+        }
+        ck(t1Has && !n1Has, "find: the expiry is on the TTL'd row only");
+    }
+
+    // Filtering. A document without expiry is ABSENT for _expires_at, so an
+    // upper bound does not match it.
+    ck(ids(c, "exp", {F::exists("_expires_at", true)}) == std::set<std::string>{"t1"},
+       "filter: _expires_at exists selects the TTL'd row");
+    ck(ids(c, "exp", {F::exists("_expires_at", false)}) == std::set<std::string>{"n1"},
+       "filter: _expires_at exists false selects the permanent row");
+    ck(ids(c, "exp", {F::lt("_expires_at", t0 + 7200000)}) == std::set<std::string>{"t1"},
+       "filter: expires before now+2h matches the TTL'd row, not the permanent one");
+    ck(ids(c, "exp", {F::gt("_expires_at", t0 + 7200000)}).empty(), "filter: nothing expires after now+2h");
+    ck(c.count("exp", {F::lt("_expires_at", t0 + 7200000)}) == 1, "count agrees");
+
+    // Changing the TTL moves it.
+    ck(c.patchWithTtl("exp", "t1", {{"touched", true}}, 60) > 0, "patchWithTtl accepted");
+    t1 = c.get("exp", "t1");
+    ck(t1 && near(*t1, nowMs() + 60000, 30000), "patchWithTtl(60) moved _expires_at to now + 60 s");
+
+    // A get-then-write round trip does not store it as a field.
+    auto copy = *c.get("exp", "t1");
+    c.insert("exp2", copy, "c1");
+    auto c1 = c.get("exp2", "c1");
+    ck(c1 && !c1->contains("_expires_at"), "a read body re-inserted without a TTL has no _expires_at");
+    ck(c1 && c1->value("name", "") == "marker", "the round trip kept the user fields");
+    copy["note"] = "updated";
+    ck(c.update("exp2", "c1", copy), "update with a read body (carrying _expires_at) succeeds");
+    c1 = c.get("exp2", "c1");
+    ck(c1 && !c1->contains("_expires_at") && c1->value("note", "") == "updated",
+       "update did not store _expires_at either");
+
+    // An export carries it, so a restore can compute the remaining TTL.
+    {
+        bool sawT1 = false, sawN1Without = false;
+        c.exportCollection("exp", false, "", [](const Client::ExportHeader&) {}, [&](Client::ExportRow&& row) {
+            if (row.id == "t1") sawT1 = row.document.contains("_expires_at");
+            if (row.id == "n1") sawN1Without = !row.document.contains("_expires_at");
+            return true;
+        });
+        ck(sawT1 && sawN1Without, "export rows carry _expires_at only where set");
+    }
+
+    // Expiry is real: a 1 s TTL row is reaped by the sweep.
+    c.insert("exp", {{"name", "short"}}, "s1", 1);
+    ck(c.get("exp", "s1").has_value(), "a 1 s row exists right after insert");
+    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
+    ck(!c.get("exp", "s1").has_value(), "and is gone after the sweep");
+
+    std::cout << "document expiry: " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 41 - 0
tests/load_test/test_document_expiry.sh

@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+# v2.19.0 e2e - a document's expiry can be read (_expires_at), filtered on,
+# exported, and is never stored from a write body.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-document-expiry
+PORT=9035
+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_document_expiry.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+"$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" > "$DIR/server.log" 2>&1 &
+SERVER_PID=$!
+trap 'kill $SERVER_PID 2>/dev/null || true; wait $SERVER_PID 2>/dev/null || true' EXIT
+for _ in $(seq 1 120); do grep -q "Notified systemd: READY" "$DIR/server.log" && break; sleep 0.5; done
+
+LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" 2>&1 | grep -v '\[error\]\|\[info\]'
+rc=${PIPESTATUS[0]}
+[[ $rc -eq 0 ]] && echo "OK - document expiry e2e passed" || { echo "FAILED"; tail -20 "$DIR/server.log"; }
+exit $rc

+ 1 - 1
tests/load_test/test_server_info.cpp

@@ -43,7 +43,7 @@ static const std::vector<const char*> kAllCaps = {
     Cap::kCompositeUnique, Cap::kBatchDeleteIds, Cap::kEventActor, Cap::kVectorReadback,
     Cap::kExportCollection, Cap::kWriteSizeGuard, Cap::kFilteredSimilarity, Cap::kServerInfo,
     Cap::kClientVersionHeader, Cap::kCollectionSchema, Cap::kEncryptionAtRest,
-    Cap::kTypedRangeFilters,
+    Cap::kTypedRangeFilters, Cap::kDocumentExpiresAt,
 };
 
 // Ordinary calls a client of any version makes; they must work across versions.

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません