|
|
@@ -282,6 +282,8 @@ bool DatabaseService::initialize() {
|
|
|
|
|
|
// v2.20.2 - rows LMDB holds that MemoryStore does not (readable, and
|
|
|
// before 2.20.2 not writable), and the reverse. Read-only, advisory.
|
|
|
+ spdlog::info("Boot: mirror-pending replay");
|
|
|
+ replayMirrorPending();
|
|
|
spdlog::info("Boot: memory/disk key audit");
|
|
|
auditMemoryDiskKeys();
|
|
|
|
|
|
@@ -1056,10 +1058,41 @@ void DatabaseService::auditSubdbPlacement() {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+void DatabaseService::recordMirrorFailure(const std::string& collection, const std::string& id) {
|
|
|
+ if (!mirror_pending_) return;
|
|
|
+ if (!mirror_pending_->append(collection, id)) {
|
|
|
+ spdlog::error("mirror-pending: could not record {}/{} in {} - if a snapshot truncates "
|
|
|
+ "its WAL entry before the next boot, only the boot key audit will find it",
|
|
|
+ collection, id, mirror_pending_->path().string());
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+void DatabaseService::replayMirrorPending() {
|
|
|
+ if (!mirror_pending_ || !store_) return;
|
|
|
+ const auto rows = mirror_pending_->load();
|
|
|
+ if (rows.empty()) return;
|
|
|
+ spdlog::warn("mirror-pending: {} row(s) whose LMDB copy failed earlier; bringing LMDB in "
|
|
|
+ "line with memory", rows.size());
|
|
|
+ const auto r = store_->syncDocStoreFromMemory(rows);
|
|
|
+ if (!mirror_pending_->replace(r.failed)) {
|
|
|
+ spdlog::error("mirror-pending: could not rewrite {}", mirror_pending_->path().string());
|
|
|
+ }
|
|
|
+ if (r.failed.empty()) {
|
|
|
+ spdlog::info("mirror-pending: repaired {} row(s): {} written, {} deleted from LMDB",
|
|
|
+ rows.size(), r.written, r.deleted);
|
|
|
+ } else {
|
|
|
+ spdlog::error("mirror-pending: {} written, {} deleted, {} still failing (kept for the "
|
|
|
+ "next boot; reads for this process are served from memory)",
|
|
|
+ r.written, r.deleted, r.failed.size());
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
void DatabaseService::auditMemoryDiskKeys() {
|
|
|
if (!projects_ || !store_) return;
|
|
|
namespace sd = smartbotic::database;
|
|
|
const auto started = std::chrono::steady_clock::now();
|
|
|
+ const std::string& diskPolicy = config_.consistencyDiskOnly;
|
|
|
+ const std::string& memPolicy = config_.consistencyMemoryOnly;
|
|
|
|
|
|
// LMDB sub-db ("project:collection") -> the MemoryStore names that feed
|
|
|
// it. A default-project collection may also live under its bare legacy
|
|
|
@@ -1081,11 +1114,17 @@ void DatabaseService::auditMemoryDiskKeys() {
|
|
|
if (i) out += ", ";
|
|
|
out += ids[i];
|
|
|
}
|
|
|
- if (ids.size() > 10) out += ", ...";
|
|
|
+ if (ids.size() > 10) out += ", ... (all in consistency-report.json)";
|
|
|
return out;
|
|
|
};
|
|
|
|
|
|
+ nlohmann::json report = {
|
|
|
+ {"policy", {{"disk_only", diskPolicy}, {"memory_only", memPolicy}}},
|
|
|
+ {"collections", nlohmann::json::array()},
|
|
|
+ };
|
|
|
uint64_t diskOnlyTotal = 0, memOnlyTotal = 0, compared = 0;
|
|
|
+ uint64_t adopted = 0, diskRemoved = 0, written = 0, memRemoved = 0, actionFailed = 0;
|
|
|
+
|
|
|
for (const auto& project : projects_->listOpen()) {
|
|
|
auto* ds = docStore(project);
|
|
|
if (!ds) continue;
|
|
|
@@ -1107,36 +1146,126 @@ void DatabaseService::auditMemoryDiskKeys() {
|
|
|
try {
|
|
|
auto disk = ds->list_ids(coll);
|
|
|
if (!disk) continue; // backend cannot list
|
|
|
- std::vector<std::string> mem;
|
|
|
- if (auto it = memNames.find(qualified); it != memNames.end()) {
|
|
|
- for (const auto& n : it->second) {
|
|
|
- for (auto& id : store_->getDocumentIds(n)) mem.push_back(std::move(id));
|
|
|
- for (auto& id : store_->getEvictedDocumentIds(n)) mem.push_back(std::move(id));
|
|
|
+ // id -> the MemoryStore name holding it (the first alias wins).
|
|
|
+ std::vector<std::pair<std::string, std::string>> mem;
|
|
|
+ const auto namesIt = memNames.find(qualified);
|
|
|
+ if (namesIt != memNames.end()) {
|
|
|
+ for (const auto& n : namesIt->second) {
|
|
|
+ for (auto& id : store_->getDocumentIds(n)) mem.emplace_back(std::move(id), n);
|
|
|
+ for (auto& id : store_->getEvictedDocumentIds(n)) mem.emplace_back(std::move(id), n);
|
|
|
}
|
|
|
}
|
|
|
- std::sort(mem.begin(), mem.end());
|
|
|
- mem.erase(std::unique(mem.begin(), mem.end()), mem.end());
|
|
|
+ std::stable_sort(mem.begin(), mem.end(),
|
|
|
+ [](const auto& a, const auto& b) { return a.first < b.first; });
|
|
|
+ mem.erase(std::unique(mem.begin(), mem.end(),
|
|
|
+ [](const auto& a, const auto& b) { return a.first == b.first; }),
|
|
|
+ mem.end());
|
|
|
std::sort(disk->begin(), disk->end()); // already key order; cheap insurance
|
|
|
|
|
|
- std::vector<std::string> diskOnly, memOnly;
|
|
|
- std::set_difference(disk->begin(), disk->end(), mem.begin(), mem.end(),
|
|
|
- std::back_inserter(diskOnly));
|
|
|
- std::set_difference(mem.begin(), mem.end(), disk->begin(), disk->end(),
|
|
|
- std::back_inserter(memOnly));
|
|
|
+ std::vector<std::string> diskOnly;
|
|
|
+ std::vector<std::pair<std::string, std::string>> memOnly; // id, memory name
|
|
|
+ {
|
|
|
+ size_t i = 0, j = 0;
|
|
|
+ while (i < disk->size() || j < mem.size()) {
|
|
|
+ if (j == mem.size() || (i < disk->size() && (*disk)[i] < mem[j].first)) {
|
|
|
+ diskOnly.push_back((*disk)[i++]);
|
|
|
+ } else if (i == disk->size() || mem[j].first < (*disk)[i]) {
|
|
|
+ memOnly.push_back(mem[j++]);
|
|
|
+ } else {
|
|
|
+ ++i; ++j;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
++compared;
|
|
|
+ if (diskOnly.empty() && memOnly.empty()) continue;
|
|
|
+
|
|
|
+ nlohmann::json entry = {{"collection", qualified}};
|
|
|
if (!diskOnly.empty()) {
|
|
|
diskOnlyTotal += diskOnly.size();
|
|
|
- spdlog::error("key audit: {}: {} row(s) on disk but not in memory - reads "
|
|
|
- "find them; before 2.20.2 every write said not-found and an "
|
|
|
- "insert of the id overwrote them; a write now loads them. "
|
|
|
- "ids: {}", qualified, diskOnly.size(), samples(diskOnly));
|
|
|
+ // Adoption needs the collection in memory (its options:
|
|
|
+ // vector dimension, TTL); one only on disk is reported.
|
|
|
+ const bool inMemory = namesIt != memNames.end();
|
|
|
+ std::vector<std::string> done, failed;
|
|
|
+ if (diskPolicy == "adopt" && inMemory) {
|
|
|
+ const std::string target = std::find(namesIt->second.begin(),
|
|
|
+ namesIt->second.end(), qualified)
|
|
|
+ != namesIt->second.end()
|
|
|
+ ? qualified : namesIt->second.front();
|
|
|
+ for (const auto& id : diskOnly) {
|
|
|
+ try {
|
|
|
+ (store_->adoptFromDocStore(target, id) ? done : failed).push_back(id);
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ spdlog::error("key audit: adopting {}/{} failed: {}", qualified, id, e.what());
|
|
|
+ failed.push_back(id);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ adopted += done.size();
|
|
|
+ } else if (diskPolicy == "remove") {
|
|
|
+ for (const auto& id : diskOnly) {
|
|
|
+ try {
|
|
|
+ ds->del(coll, id);
|
|
|
+ ds->del_vector(coll, id);
|
|
|
+ done.push_back(id);
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ spdlog::error("key audit: removing {}/{} from disk failed: {}",
|
|
|
+ qualified, id, e.what());
|
|
|
+ failed.push_back(id);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ diskRemoved += done.size();
|
|
|
+ }
|
|
|
+ actionFailed += failed.size();
|
|
|
+ const std::string action =
|
|
|
+ diskPolicy == "report" ? "reported" :
|
|
|
+ (diskPolicy == "adopt" && !inMemory) ? "reported (collection not in memory)" :
|
|
|
+ diskPolicy == "adopt" ? "adopted into memory" : "removed from disk";
|
|
|
+ spdlog::warn("key audit: {}: {} row(s) on disk but not in memory (reads find them; "
|
|
|
+ "2.20.2+ loads one when it is written) - {}{}{}. ids: {}",
|
|
|
+ qualified, diskOnly.size(), action,
|
|
|
+ diskPolicy == "report" ? "; set storage.consistency.disk_only to adopt "
|
|
|
+ "(load into memory) or remove (delete from disk)"
|
|
|
+ : "",
|
|
|
+ failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
|
|
|
+ samples(diskOnly));
|
|
|
+ entry["disk_only"] = {{"action", action}, {"ids", diskOnly}, {"failed", failed}};
|
|
|
}
|
|
|
if (!memOnly.empty()) {
|
|
|
memOnlyTotal += memOnly.size();
|
|
|
- spdlog::error("key audit: {}: {} row(s) in memory but not on disk - writes "
|
|
|
- "find them, reads served from disk do not. ids: {}",
|
|
|
- qualified, memOnly.size(), samples(memOnly));
|
|
|
+ std::vector<std::string> ids, failed;
|
|
|
+ for (const auto& [id, n] : memOnly) ids.push_back(id);
|
|
|
+ if (memPolicy == "write") {
|
|
|
+ std::vector<std::pair<std::string, std::string>> rows;
|
|
|
+ for (const auto& [id, n] : memOnly) rows.emplace_back(n, id);
|
|
|
+ const auto r = store_->syncDocStoreFromMemory(rows);
|
|
|
+ written += r.written;
|
|
|
+ for (const auto& [c, id] : r.failed) failed.push_back(id);
|
|
|
+ } else if (memPolicy == "remove") {
|
|
|
+ for (const auto& [id, n] : memOnly) {
|
|
|
+ try {
|
|
|
+ if (store_->remove(n, id, "system:consistency-repair")) ++memRemoved;
|
|
|
+ else failed.push_back(id);
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ spdlog::error("key audit: removing {}/{} from memory failed: {}",
|
|
|
+ qualified, id, e.what());
|
|
|
+ failed.push_back(id);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ actionFailed += failed.size();
|
|
|
+ const std::string action =
|
|
|
+ memPolicy == "report" ? "reported" :
|
|
|
+ memPolicy == "write" ? "written to disk" : "removed from memory";
|
|
|
+ spdlog::warn("key audit: {}: {} row(s) in memory but not on disk (writes find them, "
|
|
|
+ "reads served from disk do not) - {}{}{}. ids: {}",
|
|
|
+ qualified, memOnly.size(), action,
|
|
|
+ memPolicy == "report" ? "; set storage.consistency.memory_only to write "
|
|
|
+ "(make them readable) or remove (delete them)"
|
|
|
+ : "",
|
|
|
+ failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
|
|
|
+ samples(ids));
|
|
|
+ entry["memory_only"] = {{"action", action}, {"ids", ids}, {"failed", failed}};
|
|
|
}
|
|
|
+ report["collections"].push_back(std::move(entry));
|
|
|
} catch (const std::exception& e) {
|
|
|
spdlog::warn("key audit: {} could not be audited: {}", qualified, e.what());
|
|
|
}
|
|
|
@@ -1145,12 +1274,32 @@ void DatabaseService::auditMemoryDiskKeys() {
|
|
|
|
|
|
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
|
std::chrono::steady_clock::now() - started).count();
|
|
|
+ report["compared"] = compared;
|
|
|
+ report["disk_only"] = diskOnlyTotal;
|
|
|
+ report["memory_only"] = memOnlyTotal;
|
|
|
+ report["milliseconds"] = ms;
|
|
|
+ try {
|
|
|
+ const auto path = std::filesystem::path(config_.dataDirectory) / "consistency-report.json";
|
|
|
+ const auto tmp = path.string() + ".tmp";
|
|
|
+ {
|
|
|
+ std::ofstream out(tmp, std::ios::trunc);
|
|
|
+ out << report.dump(2) << "\n";
|
|
|
+ }
|
|
|
+ std::filesystem::rename(tmp, path);
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ spdlog::warn("key audit: could not write consistency-report.json: {}", e.what());
|
|
|
+ }
|
|
|
+
|
|
|
if (diskOnlyTotal == 0 && memOnlyTotal == 0) {
|
|
|
spdlog::info("key audit: {} collection(s) consistent ({} ms)", compared, ms);
|
|
|
} else {
|
|
|
- spdlog::error("key audit: {} collection(s) compared, {} row(s) on disk only, {} in "
|
|
|
- "memory only ({} ms). Changes nothing; see the lines above.",
|
|
|
- compared, diskOnlyTotal, memOnlyTotal, ms);
|
|
|
+ spdlog::log(actionFailed > 0 ? spdlog::level::err : spdlog::level::warn,
|
|
|
+ "key audit: {} collection(s) compared, {} row(s) on disk only, {} in "
|
|
|
+ "memory only ({} ms). Policy disk_only={} memory_only={}: {} adopted, {} "
|
|
|
+ "removed from disk, {} written to disk, {} removed from memory, {} failed. "
|
|
|
+ "Full lists: consistency-report.json in the data directory.",
|
|
|
+ compared, diskOnlyTotal, memOnlyTotal, ms, diskPolicy, memPolicy,
|
|
|
+ adopted, diskRemoved, written, memRemoved, actionFailed);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -1225,6 +1374,7 @@ bool DatabaseService::backfillIntoDocStore() {
|
|
|
}
|
|
|
if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
|
|
|
++total_failures;
|
|
|
+ recordMirrorFailure(qualified, doc.id); // v2.21.0
|
|
|
}
|
|
|
++total_docs;
|
|
|
if (total_docs % 10000 == 0) {
|
|
|
@@ -1414,6 +1564,24 @@ DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json)
|
|
|
config.bindAddress = db.value("bind_address", config.bindAddress);
|
|
|
config.rpcPort = db.value("rpc_port", config.rpcPort);
|
|
|
|
|
|
+ if (db.contains("consistency") && db["consistency"].is_object()) {
|
|
|
+ const auto& c = db["consistency"];
|
|
|
+ config.consistencyDiskOnly = c.value("disk_only", config.consistencyDiskOnly);
|
|
|
+ config.consistencyMemoryOnly = c.value("memory_only", config.consistencyMemoryOnly);
|
|
|
+ }
|
|
|
+ if (config.consistencyDiskOnly != "adopt" && config.consistencyDiskOnly != "report" &&
|
|
|
+ config.consistencyDiskOnly != "remove") {
|
|
|
+ spdlog::error("storage.consistency.disk_only '{}' is not adopt|report|remove; using report",
|
|
|
+ config.consistencyDiskOnly);
|
|
|
+ config.consistencyDiskOnly = "report";
|
|
|
+ }
|
|
|
+ if (config.consistencyMemoryOnly != "report" && config.consistencyMemoryOnly != "write" &&
|
|
|
+ config.consistencyMemoryOnly != "remove") {
|
|
|
+ spdlog::error("storage.consistency.memory_only '{}' is not report|write|remove; using report",
|
|
|
+ config.consistencyMemoryOnly);
|
|
|
+ config.consistencyMemoryOnly = "report";
|
|
|
+ }
|
|
|
+
|
|
|
// v2.4 — parse the per-listener fleet. If "listeners" is set,
|
|
|
// it overrides the legacy bind_address+rpc_port. Otherwise we
|
|
|
// synthesise one listener below using those legacy fields.
|
|
|
@@ -1795,6 +1963,11 @@ void DatabaseService::setupComponents() {
|
|
|
},
|
|
|
&mirror_healthy_,
|
|
|
&mirror_drift_count_);
|
|
|
+ mirror_pending_ = std::make_unique<smartbotic::db::storage::MirrorPendingLog>(
|
|
|
+ std::filesystem::path(config_.dataDirectory) / "mirror-pending.log");
|
|
|
+ store_->setMirrorFailureSink([this](const std::string& collection, const std::string& id) {
|
|
|
+ recordMirrorFailure(collection, id);
|
|
|
+ });
|
|
|
}
|
|
|
|
|
|
// Create persistence manager. Start from any persistenceConfig values the
|
|
|
@@ -1861,6 +2034,32 @@ void DatabaseService::setupComponents() {
|
|
|
store_->setDocumentLoadCallback([this](const std::string& collection,
|
|
|
const std::string& id,
|
|
|
uint64_t walSequence) -> std::optional<Document> {
|
|
|
+ // v2.21.0 - LMDB first. The WAL scan below finds an evicted document
|
|
|
+ // only while the WAL still holds its last write; a snapshot truncates
|
|
|
+ // that, so a document still evicted at the NEXT snapshot could not be
|
|
|
+ // read and was written as absent ("will be missing from the
|
|
|
+ // snapshot"). The next boot then came up without it while LMDB still
|
|
|
+ // had it: 7,219 such rows on one production instance. LMDB holds
|
|
|
+ // every write to an evicted document (a write reloads it first), so it
|
|
|
+ // is the right source while the mirror is healthy with no drift; the
|
|
|
+ // WAL stays the fallback for system collections and a degraded mirror.
|
|
|
+ if (projects_ && mirror_healthy_.load(std::memory_order_relaxed) &&
|
|
|
+ mirror_drift_count_.load(std::memory_order_relaxed) == 0) {
|
|
|
+ try {
|
|
|
+ const auto pc = smartbotic::database::parseProjectCollection(collection);
|
|
|
+ if (!pc.collection.empty() && pc.collection.front() != '_') {
|
|
|
+ if (auto* ds = docStore(pc.project)) {
|
|
|
+ if (auto doc = ds->get(pc.collection, id)) {
|
|
|
+ doc->collection = collection;
|
|
|
+ return doc;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ spdlog::warn("evicted {}/{}: LMDB read failed ({}); trying the WAL",
|
|
|
+ collection, id, e.what());
|
|
|
+ }
|
|
|
+ }
|
|
|
uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
|
|
|
return persistence_->loadDocument(collection, id, fromSequence);
|
|
|
});
|
|
|
@@ -2073,6 +2272,16 @@ void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& e
|
|
|
entry.collection());
|
|
|
if (auto* ds = projects_->getOrCreate(pc.project)) {
|
|
|
std::optional<Document> opt_doc(doc);
|
|
|
+ const uint64_t drift_before =
|
|
|
+ mirror_drift_count_.load(std::memory_order_relaxed);
|
|
|
+ struct RecordOnDrift { // v2.21.0 - however the block exits
|
|
|
+ DatabaseService* self; const std::string& c; const std::string& id;
|
|
|
+ uint64_t before;
|
|
|
+ ~RecordOnDrift() {
|
|
|
+ if (self->mirror_drift_count_.load(std::memory_order_relaxed) > before)
|
|
|
+ self->recordMirrorFailure(c, id);
|
|
|
+ }
|
|
|
+ } recordOnDrift{this, entry.collection(), doc.id, drift_before};
|
|
|
try {
|
|
|
smartbotic::db::storage::applyDualWriteMirror(
|
|
|
ds, mirror_healthy_, mirror_drift_count_,
|