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

fix: 2.12.1 - writes reach evicted documents; a duplicate id is AlreadyExists

An evicted document was invisible to every write path. Since v2.0 reads are
served from LMDB, so a read no longer hot-loads an evicted document, and insert,
update, updateIfVersion, upsert, patchDocument, remove, setAdd, setRemove and
restoreToVersion all looked the document up in MemoryStore only. Measured on
2.12.0 with real eviction, 200 of 200 each: patch and update said "not found";
remove returned false and the document stayed; insert with its id was accepted
and OVERWROTE it (the LMDB mirror put has no NOOVERWRITE); upsert re-created it
at version 1. Reachable wherever eviction fires: the packaged budget is 512 MB
and the estimator runs about 5x low.

MemoryStore::reloadIfEvicted() now runs in every write path, after the
in-flight guard (eviction skips in-flight ids, so the reloaded document cannot
be evicted again before the write) and before the lookup. It fails closed: if a
stub exists and the reload fails, the write throws rather than treating the
document as absent.

Found while doing what smartbotic-vectorapi asked: a duplicate primary id on
insert threw a bare runtime_error and reached clients as Internal. It is now a
typed DuplicateDocumentId (same message, still a runtime_error for internal
callers), answered as ALREADY_EXISTS with detail reason "duplicate_id" and
conflicting_id = the id; fields is empty because the identity collided, not a
field.

No wire or client change: client/ is untouched since v2.12.0 and the built
library exports the same 7174 symbols.

Test: test_evicted_writes runs the server with a 1 MB budget and no hot-write
floor so eviction really happens, asserts that it did, and gives each kind of
write its own collection. Reverting the reload fails 7 checks (150/150 each);
reverting the duplicate mapping fails 4. ctest 23/23, 14/14 e2e suites.
fszontagh 1 сар өмнө
parent
commit
95b82d0d48

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


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.12.0
+2.12.1

+ 7 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.12.0** (see `VERSION`). Last reviewed: 2026-10-07.
+**Released version: 2.12.1** (see `VERSION`). Last reviewed: 2026-10-07.
 
 > 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.0. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.12.1. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -78,6 +78,9 @@ detail and the failure modes.
 - Machine-readable refusal detail on every refused write - reason, field(s),
   value(s), conflicting id, current version (2.12.0); `Client::FailureDetail`,
   `Client::errorDetail()`
+- Writes reach EVICTED documents (2.12.1 - before it, an evicted document was
+  invisible to every write path); a duplicate id on insert is `AlreadyExists`,
+  reason `duplicate_id` (2.12.1)
 - Conditional partial update (`patchIfVersion`) and atomic increment
   (`increment`) (2.12.0)
 - Event provenance: the actor on every `DatabaseEvent`, `removeAs()`,
@@ -263,6 +266,8 @@ Two reports from smartbotic-vectorapi produced v2.11.4. Left open, with reasons:
 - **A composite constraint applies only when every component is a scalar.** An
   absent, null, object or array component leaves the row unconstrained - the SQL
   rule for NULL, extended to values that have no single key.
+- **`BatchInsert` reports failed items only as a count**, with no per-item code;
+  a duplicate id there is not distinguishable from any other failure.
 - **Most management calls still return a bare `false`.** `createRelation`,
   `configureCollection`, `createIndex`, `createCollection` and the like log the
   reason and return `false`. The `Failure&` overloads cover the five document

+ 1 - 0
docs/integration-guide.md

@@ -304,6 +304,7 @@ try {
 | `reason` | Code | Also set |
 |---|---|---|
 | `unique_violation` | `AlreadyExists` | `fields` (several for a composite), `values` (field -> value), `conflictingId` |
+| `duplicate_id` (2.12.1+) | `AlreadyExists` | `conflictingId` = the id; `fields` empty - the identity collided, not a field |
 | `missing_parent` | `FailedPrecondition` | `fields` (the reference field), `values` (the missing id), `relation` |
 | `delete_restricted` | `FailedPrecondition` | |
 | `read_only` | `FailedPrecondition` | |

+ 8 - 0
service/src/database_grpc_impl.cpp

@@ -469,6 +469,14 @@ grpc::Status DatabaseGrpcImpl::Insert(
     } catch (const nlohmann::json::exception& e) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                            "Invalid JSON: " + std::string(e.what()));
+    } catch (const DuplicateDocumentId& e) {
+        // v2.12.1 — a duplicate PRIMARY id is the caller's business exactly as
+        // a unique-index collision is; it used to fall through to INTERNAL.
+        // No field collided - the identity did - so `fields` stays empty and
+        // the reason says which kind of collision this is.
+        attachErrorDetail(context, {{"reason", "duplicate_id"},
+                                    {"conflicting_id", e.id}});
+        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — a duplicate is the caller's mistake, not a server
         // fault. MemoryStore has already undone its own mutation by the

+ 24 - 1
service/src/memory_store.cpp

@@ -346,12 +346,13 @@ std::string MemoryStore::insert(const std::string& collection, Document doc) {
     // v1.7.0 T6 quiesce: mark this doc as having an in-flight write so a
     // concurrent evictOneChunk() skips it.
     InFlightWriteGuard inFlight(*coll, doc.id);
+    reloadIfEvicted(collection, doc.id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
     // Check if ID already exists
     if (coll->documents.find(doc.id) != coll->documents.end()) {
-        throw std::runtime_error("Document with ID '" + doc.id + "' already exists");
+        throw DuplicateDocumentId(collection, doc.id);
     }
 
     // Extract vector before storing document (strips _vector from JSON data)
@@ -509,6 +510,7 @@ bool MemoryStore::update(const std::string& collection, const std::string& id, c
 
     // v1.7.0 T6 quiesce: mark before taking the write lock.
     InFlightWriteGuard inFlight(*coll, id);
+    reloadIfEvicted(collection, id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -681,6 +683,7 @@ std::string MemoryStore::upsert(const std::string& collection, Document doc) {
     // v1.7.0 T6 quiesce: mark before taking the write lock. Closes the
     // find-existing-then-write-new-version race with concurrent eviction.
     InFlightWriteGuard inFlight(*coll, doc.id);
+    reloadIfEvicted(collection, doc.id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -851,6 +854,7 @@ bool MemoryStore::remove(const std::string& collection, const std::string& id,
 
     // v1.7.0 T6 quiesce: mark before taking the write lock.
     InFlightWriteGuard inFlight(*coll, id);
+    reloadIfEvicted(collection, id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -1199,6 +1203,7 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
 
     // v1.7.0 T6 quiesce: mark before taking the write lock.
     InFlightWriteGuard inFlight(*coll, id);
+    reloadIfEvicted(collection, id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -1488,6 +1493,7 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
 
     // v1.7.0 T6 quiesce: mark before taking the write lock.
     InFlightWriteGuard inFlight(*coll, id);
+    reloadIfEvicted(collection, id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -1865,6 +1871,7 @@ uint64_t MemoryStore::count(const std::string& collection, const std::vector<Fil
 
 bool MemoryStore::setAdd(const std::string& collection, const std::string& setId, const std::string& member) {
     CollectionData* coll = getOrCreateCollection(collection);
+    reloadIfEvicted(collection, setId);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -1977,6 +1984,7 @@ bool MemoryStore::setAdd(const std::string& collection, const std::string& setId
 
 bool MemoryStore::setRemove(const std::string& collection, const std::string& setId, const std::string& member) {
     CollectionData* coll = getOrCreateCollection(collection);
+    reloadIfEvicted(collection, setId);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -2950,6 +2958,7 @@ std::optional<DocumentVersion> MemoryStore::getDocumentAtVersion(
 uint64_t MemoryStore::restoreToVersion(const std::string& collection, const std::string& id,
                                         uint64_t version, const std::string& actor) {
     CollectionData* coll = getOrCreateCollection(collection);
+    reloadIfEvicted(collection, id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
 
@@ -3427,6 +3436,20 @@ void MemoryStore::emitEvictionBurst(uint64_t docs, uint64_t bytesFreed) {
                  memoryPressureToString(pressure()));
 }
 
+void MemoryStore::reloadIfEvicted(const std::string& collection, const std::string& id) {
+    if (id.empty() || !getEvictedStub(collection, id)) return;   // the common case: resident
+    if (loadEvictedDocument(collection, id)) return;
+    // The load failed. If the stub is gone, someone else reloaded (or deleted)
+    // it meanwhile and the write may proceed against the real state. If the
+    // stub is still there, the document exists and could not be read back:
+    // refuse rather than let the write treat it as absent.
+    if (getEvictedStub(collection, id)) {
+        throw std::runtime_error("document '" + collection + "/" + id +
+                                 "' is evicted from memory and could not be reloaded; "
+                                 "refusing the write rather than treating it as absent");
+    }
+}
+
 void MemoryStore::emitPersist(const std::string& collection, const std::string& id,
                               const std::optional<Document>& doc, EventType eventType,
                               const std::optional<std::string>& actor) {

+ 25 - 0
service/src/memory_store.hpp

@@ -60,6 +60,20 @@ using EventCallback = std::function<void(const DatabaseEvent&)>;
 // or update stamps doc.updatedBy with the request's actor on every write);
 // a value - even empty - is used as given. A delete has no document left to
 // read, and a TTL expiry has no caller, so those always pass a value.
+// v2.12.1 — insert() of an id that already exists. A distinct type so the gRPC
+// layer answers ALREADY_EXISTS (reason "duplicate_id") instead of INTERNAL: a
+// duplicate primary id is the caller's business, exactly like a unique-index
+// collision. Derives from std::runtime_error with the same message, so every
+// internal caller that catches std::exception behaves as before.
+class DuplicateDocumentId : public std::runtime_error {
+public:
+    DuplicateDocumentId(std::string collection_, std::string id_)
+        : std::runtime_error("Document with ID '" + id_ + "' already exists"),
+          collection(std::move(collection_)), id(std::move(id_)) {}
+    std::string collection;
+    std::string id;
+};
+
 using PersistCallback = std::function<void(const std::string& collection,
                                            const std::string& id,
                                            const std::optional<Document>& doc,
@@ -1211,6 +1225,17 @@ private:
                      const std::optional<Document>& doc, EventType eventType,
                      const std::optional<std::string>& actor = std::nullopt);
 
+    // v2.12.1 — every write path calls this (after its InFlightWriteGuard, so
+    // the reloaded document cannot be evicted again before the write) and
+    // before looking the document up. Since v2.0 reads are served from LMDB
+    // and no longer hot-load an evicted document, so without this an evicted
+    // document was invisible to writes forever: patch/update said "not found",
+    // remove said false and left it in place, insert with its id was accepted
+    // and OVERWROTE it, upsert re-created it at version 1. Throws (fails
+    // closed) when a stub exists but the document cannot be reloaded - writing
+    // as if it did not exist is exactly the bug.
+    void reloadIfEvicted(const std::string& collection, const std::string& id);
+
     // v2.0 Stage 4 — mirror a write into the LMDB DocumentStore. Called
     // from within the per-collection write lock, BEFORE lock release, so
     // any subsequent LMDB read by any thread observes the same state as

+ 138 - 0
tests/load_test/test_evicted_writes.cpp

@@ -0,0 +1,138 @@
+// v2.12.1 client/server boundary test: writes to a document MemoryStore has
+// EVICTED, and the duplicate-id refusal.
+//
+// Since v2.0 reads are served from LMDB, so a read no longer hot-loads an
+// evicted document back into MemoryStore - and every write path looked the
+// document up in MemoryStore only. Once evicted, a document was invisible to
+// writes for the life of the process (measured on 2.12.0, 200 of 200 each):
+//   patch / update  -> "not found"
+//   remove          -> false, and the document STAYED
+//   insert same id  -> ACCEPTED, and OVERWROTE the existing document
+//   upsert          -> re-created it at version 1
+// The .sh runs the server with a tiny memory budget and no hot-write floor so
+// eviction really happens, and each collection is only used for one kind of
+// write, so every operation meets documents that are genuinely evicted.
+//
+// Also: a duplicate primary id on insert used to throw a bare runtime_error
+// and reach the client as Internal; it is now AlreadyExists, reason
+// "duplicate_id", conflictingId = the id.
+
+#include <smartbotic/database/client.hpp>
+#include <chrono>
+#include <iostream>
+#include <map>
+#include <string>
+#include <thread>
+
+using namespace smartbotic::database;
+using Code = Client::ErrorCode;
+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 int N = 150;
+static std::string id(int i) { return "d" + std::to_string(i); }
+
+int main() {
+    Client c({.address = "127.0.0.1:9019", .project = "acme"});
+    c.connect();
+
+    // ---- duplicate primary id on a RESIDENT document
+    c.insert("dup", nlohmann::json{{"n", 1}}, "x1");
+    {
+        bool typed = false;
+        Client::FailureDetail d;
+        try { c.insert("dup", nlohmann::json{{"n", 2}}, "x1"); }
+        catch (const Client::AlreadyExists& e) {
+            typed = true;
+            if (const auto* p = Client::errorDetail(e)) d = *p;
+        } catch (const std::exception&) {}
+        ck(typed, "duplicate id: AlreadyExists (was Internal)");
+        ck(d.reason == "duplicate_id", "duplicate id: reason duplicate_id, got '" + d.reason + "'");
+        ck(d.conflictingId == "x1", "duplicate id: conflictingId is the id");
+        ck(d.fields.empty(), "duplicate id: no field collided, so fields is empty");
+        auto x = c.get("dup", "x1");
+        ck(x && (*x)["n"] == 1, "duplicate id: the existing document is untouched");
+    }
+
+    // ---- force eviction
+    const std::string pad(4000, 'x');
+    const char* colls[] = {"pa", "up", "uv", "pv", "inc", "de", "in", "ups"};
+    for (const char* coll : colls)
+        for (int i = 0; i < N; ++i) c.insert(coll, nlohmann::json{{"n", i}, {"pad", pad}}, id(i));
+    std::map<std::string, uint64_t> stubs;
+    bool evicted = false;
+    for (int t = 0; t < 80 && !evicted; ++t) {
+        std::this_thread::sleep_for(std::chrono::milliseconds(500));
+        for (const auto& col : c.getMemoryStats().collections) stubs[col.collection] = col.evictedStubCount;
+        evicted = true;
+        for (const char* coll : colls) evicted = evicted && stubs["acme:" + std::string(coll)] >= N / 2;
+    }
+    ck(evicted, "eviction happened in every collection (else this test proves nothing)");
+    uint64_t minStubs = N;
+    for (const char* coll : colls) minStubs = std::min<uint64_t>(minStubs, stubs["acme:" + std::string(coll)]);
+    std::cout << "evicted at least " << minStubs << " of " << N << " in each collection\n";
+
+    int bad = 0;
+    for (int i = 0; i < N; ++i) { Client::FailureDetail f; if (c.patch("pa", id(i), {{"t", 1}}, f) == 0) ++bad; }
+    ck(bad == 0, "patch of evicted documents: " + std::to_string(bad) + " failed");
+
+    bad = 0;
+    for (int i = 0; i < N; ++i) { Client::FailureDetail f; if (!c.update("up", id(i), {{"n", i}, {"u", 1}}, f)) ++bad; }
+    ck(bad == 0, "update of evicted documents: " + std::to_string(bad) + " failed");
+
+    bad = 0;
+    for (int i = 0; i < N; ++i) {
+        auto d = c.get("uv", id(i));
+        Client::FailureDetail f;
+        if (!d || !c.updateIfVersion("uv", id(i), {{"n", i}, {"v", 1}}, (*d)["_version"].get<uint64_t>(), f)) ++bad;
+    }
+    ck(bad == 0, "updateIfVersion of evicted documents: " + std::to_string(bad) + " failed");
+
+    bad = 0;
+    for (int i = 0; i < N; ++i) {
+        auto d = c.get("pv", id(i));
+        Client::FailureDetail f;
+        if (!d || c.patchIfVersion("pv", id(i), {{"claimed", true}}, (*d)["_version"].get<uint64_t>(), f) == 0) ++bad;
+    }
+    ck(bad == 0, "patchIfVersion of evicted documents: " + std::to_string(bad) + " failed");
+
+    bad = 0;
+    for (int i = 0; i < N; ++i) {
+        Client::FailureDetail f;
+        auto r = c.increment("inc", id(i), {{"n", 1000}}, f);
+        if (!r || (*r)["n"] != i + 1000) ++bad;
+    }
+    ck(bad == 0, "increment of evicted documents (from their REAL value): " + std::to_string(bad) + " wrong");
+
+    int falseDel = 0, survived = 0;
+    for (int i = 0; i < N; ++i) if (!c.remove("de", id(i))) ++falseDel;
+    for (int i = 0; i < N; ++i) if (c.exists("de", id(i))) ++survived;
+    ck(falseDel == 0 && survived == 0, "remove of evicted documents: " + std::to_string(falseDel) +
+       " reported false, " + std::to_string(survived) + " survived");
+
+    int accepted = 0, overwritten = 0, notDupId = 0;
+    for (int i = 0; i < N; ++i) {
+        try { c.insert("in", nlohmann::json{{"marker", "OVERWRITE"}}, id(i)); ++accepted; }
+        catch (const Client::AlreadyExists& e) {
+            const auto* d = Client::errorDetail(e);
+            if (!d || d->reason != "duplicate_id") ++notDupId;
+        } catch (const std::exception&) { ++notDupId; }
+        auto d = c.get("in", id(i));
+        if (d && d->contains("marker")) ++overwritten;
+    }
+    ck(accepted == 0 && overwritten == 0, "insert over evicted documents: " + std::to_string(accepted) +
+       " accepted, " + std::to_string(overwritten) + " overwritten");
+    ck(notDupId == 0, "insert over evicted documents is refused as duplicate_id");
+
+    int reset = 0;
+    for (int i = 0; i < N; ++i) {
+        c.upsert("ups", nlohmann::json{{"n", i}, {"again", true}}, id(i));
+        auto d = c.get("ups", id(i));
+        if (!d || (*d)["_version"].get<uint64_t>() == 1) ++reset;
+    }
+    ck(reset == 0, "upsert of evicted documents keeps their history: " + std::to_string(reset) + " restarted at version 1");
+
+    std::cout << "\npassed=" << pass << " failed=" << fail << "\n";
+    return fail == 0 ? 0 : 1;
+}

+ 80 - 0
tests/load_test/test_evicted_writes.sh

@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# v2.12.0 client/server boundary e2e - writes to EVICTED documents, over real gRPC,
+# with a memory budget small enough that eviction really happens. See
+# test_evicted_writes.cpp for what each assertion covers.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-evicted-writes
+PORT=9019
+
+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 },
+    "memory": {
+      "max_memory_mb": 1,
+      "eviction_threshold_percent": 50,
+      "eviction_target_percent": 20,
+      "eviction_check_interval_ms": 200,
+      "hot_write_floor_ms": 0,
+      "memory_soft_percent": 50,
+      "memory_hard_percent": 2000,
+      "memory_emergency_percent": 4000
+    }
+  }
+}
+CFG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_evicted_writes.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+boot() {
+    "$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" \
+        > "$DIR/server-$1.log" 2>&1 &
+    SERVER_PID=$!
+    for _ in $(seq 1 60); do
+        grep -q "Notified systemd: READY" "$DIR/server-$1.log" && return 0
+        sleep 0.5
+    done
+    echo "server failed to become ready; log:"
+    tail -30 "$DIR/server-$1.log"
+    exit 1
+}
+stop() { kill "$SERVER_PID" 2>/dev/null || true; wait "$SERVER_PID" 2>/dev/null || true; }
+trap stop EXIT
+
+run() {   # run <phase>
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1"
+    local rc=$?
+    set -e
+    if [[ $rc -ne 0 ]]; then
+        echo ""
+        echo "FAILED in phase $1 - server log tail:"
+        tail -30 "$DIR"/server-*.log | tail -30
+        exit $rc
+    fi
+}
+
+echo "=== running ==="
+boot 1
+run only
+
+echo ""
+echo "OK - evicted writes e2e passed"

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