| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601 |
- #include "database_service.hpp"
- #include "json_parse.hpp"
- #include "project_addressing.hpp"
- #include "storage/secondary_index.hpp"
- #include "storage/document_store.hpp"
- #include "storage/document_store_lmdb.hpp"
- #include "storage/dual_write_mirror.hpp"
- #include "relations/relation_cascade.hpp"
- #include "relations/relation_enforcement.hpp"
- #include "auth/auth_interceptor.hpp"
- #include "auth/principal.hpp"
- #include "tls/cert_generator.hpp"
- #include <fstream>
- #include <sstream>
- #include <map>
- #include <set>
- #include <algorithm>
- #include <chrono>
- #include <iterator>
- #include "storage/lmdb_env.hpp"
- #include "storage/migrate_v1_to_v2.hpp"
- #include "storage/project_store.hpp"
- #include "storage/subdb_placement.hpp"
- #include <grpcpp/grpcpp.h>
- #include <grpcpp/resource_quota.h>
- #include <spdlog/spdlog.h>
- #include <fstream>
- #ifdef HAVE_SYSTEMD
- #include <systemd/sd-daemon.h>
- #endif
- #if defined(__GLIBC__) && !defined(__APPLE__)
- #include <malloc.h>
- #endif
- namespace smartbotic::database {
- DatabaseService::DatabaseService(Config config)
- : config_(std::move(config))
- {
- }
- DatabaseService::~DatabaseService() {
- stop();
- }
- std::string DatabaseService::readOnlyReason() const {
- std::lock_guard<std::mutex> lock(reason_mutex_);
- return read_only_reason_;
- }
- void DatabaseService::setReadOnly(bool value, const std::string& reason) {
- {
- std::lock_guard<std::mutex> lock(reason_mutex_);
- read_only_reason_ = value ? reason : "";
- }
- bool prev = read_only_.exchange(value, std::memory_order_acq_rel);
- if (prev != value) {
- if (value) {
- spdlog::error("Database entered READ-ONLY mode: {}", reason);
- } else {
- spdlog::info("Database unlocked -- writes accepted");
- }
- }
- }
- bool DatabaseService::initialize() {
- spdlog::info("Initializing database service (node: {})", config_.nodeId);
- try {
- // Create data directory if needed
- std::error_code ec;
- std::filesystem::create_directories(config_.dataDirectory, ec);
- if (ec) {
- spdlog::error("Failed to create data directory: {}", ec.message());
- return false;
- }
- setupComponents();
- // Initialize encryption
- if (config_.encryptionEnabled) {
- if (!encryption_->initialize()) {
- spdlog::error("Failed to initialize encryption");
- return false;
- }
- }
- // Recover from persistence
- recovery_outcome_ = persistence_->recover(*store_);
- #if defined(__GLIBC__) && !defined(__APPLE__)
- // v1.9.3 — release freelist pages accumulated during recovery. v1.9.1
- // added trim at end of loadSnapshot, but the WAL replay phase that
- // runs afterward (`persistence_->recover`'s `replayWal` step) also
- // burns through GBs of small Document JSON allocations whose pages
- // sit on the per-thread freelist with no subsequent allocation to
- // shake them loose. On Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md update 15:05)
- // this was 5.7 GB at 23 min uptime — fully reclaimable via
- // malloc_trim, just nothing called it. Paired with the periodic
- // every-5-minute trim in MemoryStore::logMemoryCheck, so any
- // post-boot bloat that escapes this trim gets cleaned up shortly.
- ::malloc_trim(0);
- #endif
- if (recovery_outcome_.isFailure()) {
- const std::string modeStr =
- recoveryModeToString(config_.persistenceConfig.recoveryMode);
- spdlog::error("");
- spdlog::error("+------------------------------------------------------------------+");
- spdlog::error("| RECOVERY REFUSED |");
- spdlog::error("| |");
- spdlog::error("| Mode: {}", modeStr);
- spdlog::error("| Expected snapshot: {}", recovery_outcome_.expectedSnapshot.string());
- spdlog::error("| Reason: {}", recovery_outcome_.failureReason);
- spdlog::error("| |");
- spdlog::error("| Snapshots available: {}", recovery_outcome_.snapshotsAvailable);
- spdlog::error("| Snapshots attempted: {}", recovery_outcome_.snapshotsAttempted);
- spdlog::error("| |");
- spdlog::error("| To escalate, restart with one of: |");
- spdlog::error("| --recovery-mode=snapshot_fallback Try older snapshots |");
- spdlog::error("| --recovery-mode=wal_only Replay WAL only (slow) |");
- spdlog::error("| --recovery-mode=best_effort Try all of the above |");
- spdlog::error("| --recovery-mode=force_empty Start empty (LAST RESORT) |");
- spdlog::error("| |");
- spdlog::error("| Or set in config.json: \"recovery\": {{ \"mode\": \"<mode>\" }} |");
- spdlog::error("| |");
- spdlog::error("| PRESERVE /var/lib/smartbotic-database/ BEFORE ESCALATING. |");
- spdlog::error("+------------------------------------------------------------------+");
- throw std::runtime_error("recovery failed; refusing to start");
- }
- // Auto-readonly mode on non-trivial recovery
- if (recovery_outcome_.isNonTrivial() && !force_readwrite_) {
- std::string reason;
- switch (recovery_outcome_.kind) {
- case RecoveryOutcome::Kind::SnapshotFellBack:
- reason = "fell back to snapshot " +
- recovery_outcome_.snapshotUsed.filename().string() +
- " because " +
- recovery_outcome_.expectedSnapshot.filename().string() +
- " failed: " + recovery_outcome_.failureReason;
- break;
- case RecoveryOutcome::Kind::WalOnlyReplay:
- reason = "WAL-only replay, no snapshot loaded (" +
- std::to_string(recovery_outcome_.walEntriesReplayed) +
- " entries)";
- break;
- case RecoveryOutcome::Kind::ForcedEmpty:
- reason = "forced empty by operator (--recovery-mode=force_empty)";
- break;
- default:
- reason = "non-trivial recovery";
- break;
- }
- reason += ". Run `smartbotic-db-cli unlock` to accept this state, "
- "or restart with --force-readwrite to bypass this check.";
- setReadOnly(true, reason);
- spdlog::error("");
- spdlog::error("+------------------------------------------------------------------+");
- spdlog::error("| [ERROR] Database booted in READ-ONLY mode after non-trivial |");
- spdlog::error("| recovery. |");
- spdlog::error("| |");
- spdlog::error("| Reason: {}", reason);
- spdlog::error("| |");
- spdlog::error("| Writes will be REJECTED until you acknowledge this state: |");
- spdlog::error("| smartbotic-db-cli unlock # live, no restart |");
- spdlog::error("| smartbotic-database --force-readwrite # on next restart |");
- spdlog::error("+------------------------------------------------------------------+");
- }
- // Set replication sequence after recovery (WAL sequence is now known)
- replication_->setSequence(persistence_->currentWalSequence());
- // v1.8.0 — start the persistence manager before loadFromStore /
- // migrations so any system-collection writes those phases produce
- // (view docs, _collection_meta entries, _migrations recordings)
- // reach the WAL like normal mutations. Pre-v1.8, persistence_ was
- // started later in start(), which silently dropped those writes
- // (running_=false → logInsert no-op). That meant migrated views
- // only "survived" because the runner re-created them every boot,
- // and a manually-created view that landed during the racy startup
- // window (before full readiness) could be lost.
- if (!persistence_->start()) {
- spdlog::error("Failed to start persistence manager before migrations");
- return false;
- }
- // Load view definitions from the _views system collection (which is now
- // populated by the persistence recovery above).
- view_manager_->loadFromStore();
- // Load per-collection configs from the _collection_meta system collection.
- // Must happen AFTER persistence recovery and BEFORE migrations so any
- // migration-created documents are stamped with the correct precision.
- config_manager_->loadFromStore();
- policy_manager_->loadFromStore();
- relation_manager_->loadFromStore();
- applyRelationDeclarations();
- // v2.11.0 close-out — teach the TTL sweeper about relations. Installed
- // HERE, after loadFromStore() and the arming pass, deliberately: the
- // hook consults the declaration cache and the reverse index, and an
- // expiry that fired before either was ready would have decided from an
- // empty cache. Until this line the sweeper behaves exactly as it did
- // pre-v2.11.0 (which is also what every unit fixture that never
- // installs the hook keeps doing).
- store_->setTtlExpiryRelationHook(
- [this](const std::string& qualifiedCollection, const std::string& id,
- bool firstAttempt) {
- return ttlExpiryRelationDecision(qualifiedCollection, id, firstAttempt);
- });
- // v2.9.0 — re-apply persisted index declarations to each project's LMDB
- // store. This is load-bearing, not bookkeeping: the declaration is what
- // makes the write path maintain an index, and the planner consults an
- // index purely on the declaration's word. If this step were skipped, a
- // restart would leave indexes recorded but unmaintained, and queries
- // would be served from a frozen index - stale rows returned as current,
- // with nothing logged.
- applyIndexDeclarations();
- applySchemaDeclarations(); // v2.16.0
- // v2.11.0 final review (finding 4) — THE POST-REPLAY RE-MIRROR PASS
- // RUNS HERE, and the position is load-bearing.
- //
- // PersistenceManager::recover() (above, before any of the arming
- // steps) only collects the id list. The pass writes documents through
- // LmdbDocumentStore::put(), which reads indexed_fields(),
- // unique_fields() and relations() LIVE and maintains every index
- // inside the document's own write transaction. Run from inside
- // recover(), all three maps were still empty, so it repaired the
- // document and left every posting derived from it stale: an
- // index-served query then returns the row under its OLD value and
- // misses it under its new one - silently wrong rows, which is exactly
- // what putting maintainIndexes() inside the transaction exists to
- // prevent, and which bit any install with a v2.9 index declared
- // whether or not it uses relations. It also made the reverse-index
- // half of relation_cascade.hpp's convergence claim false, and made
- // UniqueViolation (and therefore the pass's own retry phase)
- // unreachable.
- //
- // Must be after applyRelationDeclarations() AND
- // applyIndexDeclarations(); backfillIntoDocStore() below already sits
- // at this point for the same reason. Never throws.
- persistence_->runPendingRemirror(*store_, recovery_outcome_);
- // Run migrations if enabled
- if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
- if (!runMigrations()) {
- if (config_.migrations.failOnError) {
- spdlog::error("Failed to run migrations");
- return false;
- }
- spdlog::warn("Some migrations failed, continuing anyway");
- }
- }
- // v2.0 Stage 4 — synchronous backfill into doc_store_ before
- // serving. Without this, only post-boot writes land in LMDB and
- // the read-flip downstream would see an empty mirror.
- backfillIntoDocStore();
- // v2.4.4 — placement audit. Reports documents sitting in a sub-db
- // other than the one they declare, which is the signature of a
- // misbound MDB_dbi (see storage/subdb_identity.hpp). Read-only and
- // advisory: it never blocks startup, because a misplacement is a
- // data-location problem an operator repairs offline with
- // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
- // service on the other 99% of the dataset.
- // 2.20.1 - each remaining boot step logs its start, so a boot that
- // dies here (a production crash loop on 2026-10-19 died about 3 s
- // after the backfill line, with nothing logged) shows which step.
- spdlog::info("Boot: sub-db placement audit");
- auditSubdbPlacement();
- // 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();
- // v2.6.0 — stamp `project: "default"` onto file records written before
- // files were namespaced. Idempotent, and advisory: a file-metadata
- // stamp is not a reason to refuse service, so failures warn only.
- if (files_) {
- spdlog::info("Boot: file records");
- try {
- const uint32_t stamped = files_->stampMissingProjects();
- if (stamped > 0) {
- spdlog::info("v2.6.0 file migration: stamped {} legacy file "
- "record(s) with project 'default'", stamped);
- } else {
- spdlog::debug("v2.6.0 file migration: no legacy file records");
- }
- } catch (const std::exception& e) {
- spdlog::warn("v2.6.0 file migration failed: {}", e.what());
- }
- }
- // v2.11.0 close-out — LAST ACT OF THE BOOT PATH, and the position is
- // load-bearing. Everything above that can bump the drift counter (the
- // post-replay re-mirror pass, backfillIntoDocStore(), a malformed
- // legacy collection key) is now behind the baseline, so
- // mirrorDriftSinceReady() reports only drift a LIVE write caused.
- // Destructive relation policies gate on that, not on the raw counter:
- // see MemoryStore::markMirrorDriftBaseline() for the trap this closes
- // (one unrepairable row disabling every cascade/set_null delete and
- // every CreateRelation for the process's life, with an error message
- // telling the operator to restart, which re-incurs it). Reads keep
- // gating on the RAW counter - a stale row genuinely means MemoryStore
- // is ahead, and that fallback must stay.
- // v2.17.0 - encrypt what must be encrypted, and remove the plaintext
- // copies, before anything can read or replicate them.
- spdlog::info("Boot: encryption at rest");
- migrateEncryptionAtRest();
- store_->markMirrorDriftBaseline();
- if (store_->mirrorDriftBaseline() > 0) {
- spdlog::warn("mirror drift at READY: {} - accrued on the boot path (see the "
- "ERROR lines above for the exact rows). Reads for this process "
- "will be served from MemoryStore rather than LMDB. Destructive "
- "relation policies are NOT disabled by this, but the rows named "
- "above are still stale in LMDB until each is rewritten through "
- "an ordinary write; a restart re-attempts and, if the cause "
- "persists, re-incurs the same count.",
- store_->mirrorDriftBaseline());
- }
- spdlog::info("Database service initialized successfully");
- return true;
- } catch (const std::exception& e) {
- spdlog::error("Failed to initialize database service: {}", e.what());
- return false;
- }
- }
- void DatabaseService::migrateLegacyEnvToDefaultProject() {
- const auto legacy = config_.dataDirectory / "env";
- const auto target = config_.dataDirectory / "projects" /
- smartbotic::database::kDefaultProject / "env";
- std::error_code ec;
- const bool legacy_exists = std::filesystem::exists(legacy, ec);
- const bool target_exists = std::filesystem::exists(target, ec);
- if (!legacy_exists) return; // fresh install or already migrated
- if (target_exists) {
- spdlog::error("v2.3 storage: both legacy '{}' and new '{}' exist — "
- "refusing to start. Inspect manually; the safe move is "
- "to either delete the legacy dir (if you confirm it's a "
- "leftover) or stop and contact ops.",
- legacy.string(), target.string());
- throw std::runtime_error("v2.3 storage migration: ambiguous layout");
- }
- std::filesystem::create_directories(target.parent_path(), ec);
- if (ec) {
- throw std::runtime_error("v2.3 storage migration: cannot create '"
- + target.parent_path().string() + "': " + ec.message());
- }
- std::filesystem::rename(legacy, target, ec);
- if (ec) {
- throw std::runtime_error("v2.3 storage migration: rename '"
- + legacy.string() + "' -> '"
- + target.string() + "' failed: " + ec.message());
- }
- spdlog::info("v2.3 storage: migrated legacy env '{}' -> '{}' (default project)",
- legacy.string(), target.string());
- }
- smartbotic::db::storage::DocumentStore* DatabaseService::docStore() noexcept {
- return docStore(smartbotic::database::kDefaultProject);
- }
- smartbotic::db::storage::DocumentStore*
- DatabaseService::docStore(std::string_view project) noexcept {
- if (!projects_) return nullptr;
- return projects_->get(project);
- }
- std::vector<std::string> DatabaseService::listProjects() const {
- if (!projects_) return {};
- return projects_->listOnDisk();
- }
- bool DatabaseService::createProject(const std::string& name, std::string& error) {
- if (!projects_) {
- error = "project registry not initialized";
- return false;
- }
- return projects_->create(name, error);
- }
- bool DatabaseService::dropProject(const std::string& name, std::string& error) {
- if (!projects_) {
- error = "project registry not initialized";
- return false;
- }
- // v2.11.0 close-out — capture the relation declarations belonging to this
- // project BEFORE the drop. Relations are validated same-project at
- // creation (no LMDB transaction spans two envs), so `child` and `parent`
- // are always in the same project as `name` itself; listRelations(name)
- // therefore names every declaration the drop invalidates. Captured first
- // because listRelations needs the project to still be nameable and, more
- // importantly, because un-arming needs the store to still exist.
- std::vector<RelationInfo> doomed;
- if (relation_manager_) {
- try {
- doomed = relation_manager_->listRelations(name);
- } catch (const std::exception& e) {
- spdlog::warn("v2.11 relations: could not enumerate relations of project '{}' "
- "before dropping it ({}); its declarations may be left behind",
- name, e.what());
- }
- }
- if (!projects_->drop(name, error)) return false;
- // v2.12.2 - collection configs live in the GLOBAL `_collection_meta`, not
- // in the project's env, so dropping the env left every one of the project's
- // declarations behind - and a recreated project silently inherited them.
- // The index sub-dbs went with the env; only the records remain to remove.
- if (config_manager_) {
- const std::string prefix = name + ":";
- size_t removed = 0;
- for (const auto& [key, cfg] : config_manager_->allConfigs()) {
- if (key.rfind(prefix, 0) == 0 && config_manager_->removeConfig(key)) ++removed;
- }
- if (removed > 0) {
- spdlog::info("dropProject '{}': removed {} collection config(s)", name, removed);
- }
- }
- // ---- The drop succeeded; the declarations now point at a namespace that
- // no longer exists. Sweep them out of the global `_relations` collection
- // and un-arm each affected child collection.
- //
- // Order (drop first, sweep second) is deliberate: the registry is the one
- // that refuses "default" and rejects unknown names, so sweeping first would
- // destroy declarations for a project whose drop then failed. The cost of
- // this order is that the per-project store is usually already gone by the
- // time we try to un-arm, which makes the un-arm a no-op - correct, since a
- // store that no longer exists cannot be maintaining a reverse index. It
- // still runs, because ProjectStoreRegistry may hold a live
- // LmdbDocumentStore for a re-created project of the same name.
- //
- // ⚠ Advisory, never fatal: the project IS dropped at this point, and a
- // leftover declaration is litter, not corruption (its child and parent
- // collections are both gone, so nothing can be enforced against them). A
- // failure here must not report the drop as failed.
- for (const auto& r : doomed) {
- try {
- std::string err;
- if (!relation_manager_->dropRelation(r.name, err)) {
- spdlog::warn("v2.11 relations: could not drop declaration '{}' left by "
- "dropped project '{}': {}", r.name, name, err);
- continue;
- }
- const auto rc = resolveCollection(r.child);
- auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
- docStore(rc.project));
- if (lmdb != nullptr) {
- // Empty list = "this collection has no relations", which is what
- // set_relations replaces the previous list with. Every relation
- // of a dropped project goes, so clearing the child wholesale is
- // exactly right here (unlike DropRelation, which must re-arm the
- // survivors).
- lmdb->set_relations(rc.collection, {});
- }
- spdlog::info("v2.11 relations: dropped declaration '{}' with the project '{}'",
- r.name, name);
- } catch (const std::exception& e) {
- spdlog::warn("v2.11 relations: could not clean up declaration '{}' after "
- "dropping project '{}': {}", r.name, name, e.what());
- }
- }
- // ⚠ KNOWN, NOT FIXED HERE (v2.11.0 close-out): _views, _policies and
- // _collection_meta have the SAME gap - ProjectStoreRegistry::drop() removes
- // the project's env and nothing else, so a dropped project leaves its view
- // definitions, access policies and per-collection configs behind in those
- // global system collections too. Not a shared fix: each manager keys and
- // caches differently (ViewManager keys `<project>:<name>`, PolicyManager
- // `<project>:<principal>`, CollectionConfigManager `<project>:<collection>`
- // and canonicalises the cache key only), so each needs its own sweep, and
- // PolicyManager's has a security dimension this one does not (a re-created
- // project inheriting a stale policy). Scoped out deliberately; recorded so
- // it is not rediscovered as new.
- return true;
- }
- bool DatabaseService::runMigrations() {
- if (!config_.migrations.enabled) {
- return true;
- }
- MigrationRunner::Config migrationConfig;
- migrationConfig.directory = config_.migrations.directory;
- migrationConfig.autoApply = config_.migrations.autoApply;
- migrationConfig.failOnError = config_.migrations.failOnError;
- migrationRunner_ = std::make_unique<MigrationRunner>(
- *store_, *view_manager_, *relation_manager_, migrationConfig);
- migrationRunner_->setDocumentPreparer([this](const std::string& collection, Document& doc) {
- encryption_->encryptSensitiveFields(doc, encryptionRuleFor(collection)); // v2.17.0
- });
- const bool ok = migrationRunner_->runMigrations();
- // v2.11.0 close-out — a `create_relation` migration op only PERSISTS the
- // declaration. Arming the write path and building the reverse index over
- // rows that already exist is what applyRelationDeclarations() does, and it
- // has already run for this boot (initialize() calls it before migrations),
- // so without this a migration-declared relation would maintain no reverse
- // index and enforce nothing until the NEXT restart - the "declared but not
- // enforcing" state this feature's self-heal exists to make unreachable.
- // Idempotent and cheap: re-arming an already-armed child replaces an
- // identical list, and the bootstrap loop skips any relation whose index
- // sub-db already exists. Runs even when the migration run reported failure,
- // because a partially-applied run may still have created a relation.
- applyRelationDeclarations(/*afterMigrations=*/true);
- return ok;
- }
- nlohmann::json DatabaseService::schemaView(const nlohmann::json& body) const {
- nlohmann::json copy = body;
- if (copy.is_object()) {
- stripReservedFields(copy);
- copy.erase("_vector");
- }
- encryption_->decryptTree(copy);
- return copy;
- }
- DatabaseService::AtRestStats DatabaseService::encryptCollectionAtRest(const std::string& collection) {
- AtRestStats st;
- if (!encryption_ || !encryption_->isEnabled()) return st;
- const EncryptionRule rule = encryptionRuleFor(collection);
- const auto transform = [&](nlohmann::json& body) { return encryption_->encryptTree(body, rule); };
- // LMDB holds every row (MemoryStore may have evicted some); find the rows
- // that still hold plaintext, then rewrite each under the collection lock.
- smartbotic::db::storage::DocumentStore* ds = nullptr;
- std::string bare;
- // The names MemoryStore may hold this collection's rows under: the
- // qualified form and, in the default project, the bare one (see
- // MemoryStore::encryptionOptionsFor). Both map to the same LMDB sub-db.
- std::vector<std::string> names{collection};
- try {
- const auto rc = smartbotic::database::resolveCollection(collection);
- ds = docStore(rc.project);
- bare = rc.collection;
- if (rc.qualified != collection) names.push_back(rc.qualified);
- if (rc.project == smartbotic::database::kDefaultProject && rc.collection != collection) {
- names.push_back(rc.collection);
- }
- } catch (const std::exception&) {
- }
- std::vector<std::string> ids;
- if (ds != nullptr) {
- ds->export_scan(bare, "", false, nullptr, [](uint64_t) {},
- [&](Document&& d, smartbotic::db::storage::DocumentStore::ExportVectorState,
- const float*, size_t) -> bool {
- ++st.scanned;
- EncryptionManager::TreeAudit a;
- encryption_->auditTree(d.data(), rule, a);
- if (a.plaintextRequired > 0) ids.push_back(d.id);
- return true;
- });
- }
- for (const auto& id : ids) {
- int r = -1;
- for (const auto& n : names) {
- r = store_->rewriteBodyInPlace(n, id, transform);
- if (r != -1) break;
- }
- if (r == 1) {
- ++st.rewritten;
- } else if (r == -1 && ds != nullptr) {
- // Not in MemoryStore at all: the LMDB row is the only copy.
- if (auto d = ds->get(bare, id)) {
- nlohmann::json b = d->data();
- if (transform(b)) {
- d->set_data(b);
- d->encrypted = true;
- ds->put(bare, id, *d);
- ++st.lmdbOnly;
- }
- }
- }
- }
- if (history_store_) {
- for (const auto& n : names) {
- st.versions += history_store_->rewrite(n, [&](DocumentVersion& v) {
- nlohmann::json b = v.data();
- if (!transform(b)) return false;
- v.set_data(b);
- v.encrypted = true;
- return true;
- });
- }
- }
- return st;
- }
- void DatabaseService::requestResealAtNextBoot(const std::string& project) {
- std::ofstream(config_.dataDirectory / "encryption-reseal.pending", std::ios::app)
- << (project.empty() ? "*" : project) << "\n";
- }
- void DatabaseService::migrateEncryptionAtRest() {
- namespace fs = std::filesystem;
- const fs::path marker = config_.dataDirectory / "encryption-at-rest.v1";
- const fs::path reseal = config_.dataDirectory / "encryption-reseal.pending";
- std::error_code ec;
- const bool firstRun = !fs::exists(marker, ec);
- const bool resealPending = fs::exists(reseal, ec);
- if (!encryption_ || !encryption_->isEnabled()) {
- if (firstRun) spdlog::warn("v2.17 at-rest: encryption is disabled; nothing is encrypted at rest");
- return;
- }
- if (!firstRun && !resealPending) return;
- AtRestStats total;
- if (firstRun) {
- spdlog::warn("v2.17 at-rest: one-time migration - encrypting values stored in plaintext "
- "that must be encrypted (encrypted collections, sensitive_fields, the "
- "sensitive name patterns at any depth)");
- std::set<std::string> done; // canonical names: aliases share one LMDB sub-db
- for (const auto& coll : store_->listCollections()) {
- if (coll.empty() || coll[0] == '_') continue;
- std::string canonical = coll;
- try {
- canonical = smartbotic::database::resolveCollection(coll).qualified;
- } catch (const std::exception&) {
- }
- if (!done.insert(canonical).second) continue;
- #ifdef HAVE_SYSTEMD
- // Each collection is a scan plus a history rewrite: on a large
- // dataset the whole pass outlasts TimeoutStartSec. Same protocol
- // the v1 migration and recovery use.
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- sd_notify(0, ("STATUS=Encrypting at rest: " + canonical).c_str());
- #endif
- const auto s = encryptCollectionAtRest(canonical);
- total.scanned += s.scanned;
- total.rewritten += s.rewritten;
- total.lmdbOnly += s.lmdbOnly;
- total.versions += s.versions;
- if (s.rewritten + s.lmdbOnly + s.versions > 0) {
- spdlog::warn("v2.17 at-rest: {}: {} row(s) and {} history version(s) encrypted "
- "(of {} row(s) scanned)", canonical, s.rewritten + s.lmdbOnly, s.versions,
- s.scanned);
- }
- }
- spdlog::warn("v2.17 at-rest: {} row(s) scanned, {} encrypted in place ({} LMDB-only), "
- "{} history version(s) encrypted", total.scanned,
- total.rewritten + total.lmdbOnly, total.lmdbOnly, total.versions);
- }
- // The seal: the rewrite replaced plaintext in the live stores, but older
- // snapshots, the WAL and LMDB's freed pages still hold it.
- std::string err;
- size_t snaps = 0, wals = 0;
- if (!persistence_->sealAfterRewrite(*store_, err, snaps, wals)) {
- spdlog::error("v2.17 at-rest: seal FAILED ({}); old plaintext copies remain in the WAL / "
- "snapshots. Serving continues; the next boot retries.", err);
- requestResealAtNextBoot();
- return;
- }
- // v2.17.2 - which envs to compact. The first run compacts every project.
- // A reseal compacts only the projects named in the pending file; "*" (a
- // failure path) or a pre-2.17.2 file (its content was "1") means all.
- // 2.17.1 compacted every project on any reseal: a 262 MB env the upgrade
- // never touched cost 2.5 minutes of a restart and reclaimed nothing.
- bool compactAll = firstRun;
- std::set<std::string> toCompact;
- if (!firstRun) {
- std::ifstream in(reseal);
- std::string line;
- while (std::getline(in, line)) {
- if (line.empty()) continue;
- if (line == "*" || line == "1") compactAll = true;
- else toCompact.insert(line);
- }
- if (toCompact.empty()) compactAll = true;
- }
- size_t compacted = 0;
- for (const auto& p : projects_->listOpen()) {
- if (!compactAll && !toCompact.count(p)) continue;
- ++compacted;
- uint64_t before = 0, after = 0;
- std::string cerr;
- if (projects_->compact(p, before, after, cerr)) {
- spdlog::info("v2.17 at-rest: project '{}' compacted, {} -> {} bytes", p, before, after);
- } else {
- spdlog::error("v2.17 at-rest: project '{}' compaction failed: {} - freed pages may "
- "still hold old plaintext; the next boot retries", p, cerr);
- requestResealAtNextBoot(p);
- applyIndexDeclarations();
- applyRelationDeclarations(/*afterMigrations=*/true);
- return;
- }
- }
- // Compaction reopened every env: per-store arming must be applied again.
- applyIndexDeclarations();
- applyRelationDeclarations(/*afterMigrations=*/true);
- std::ofstream(marker) << "encrypted at rest by 2.17.0\n";
- fs::remove(reseal, ec);
- spdlog::warn("v2.17 at-rest: sealed - {} old snapshot(s) and {} WAL file(s) removed, {} "
- "project(s) compacted{}. Copies made BEFORE this boot (backups, pre-upgrade copies, "
- "replicas, disk blocks) are outside the database's reach.", snaps, wals, compacted,
- compactAll ? " (all)" : "");
- }
- void DatabaseService::applySchemaDeclarations() {
- size_t armed = 0;
- for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
- if (!cfg.schema) continue;
- auto compiled = smartbotic::db::schema::compile(*cfg.schema);
- if (!compiled.schema) {
- // Loud: the record says this collection is constrained and it is
- // not. Only a hand-edited record can get here (the RPC refuses
- // anything that does not compile).
- spdlog::error("v2.16 schema: the schema stored for {} does not compile ({}); "
- "it is NOT enforced until it is set again", qualified, compiled.error);
- continue;
- }
- auto entry = std::make_shared<smartbotic::db::schema::SchemaEntry>();
- entry->compiled = compiled.schema;
- entry->source = *cfg.schema;
- entry->audit = cfg.schemaMode == "audit";
- schemas_.set(qualified, entry);
- ++armed;
- spdlog::info("v2.16 schema: {} armed ({})", qualified, entry->audit ? "audit" : "enforce");
- }
- if (armed > 0) spdlog::info("v2.16 schema: {} collection schema(s) armed", armed);
- }
- void DatabaseService::applyIndexDeclarations() {
- size_t applied = 0;
- for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
- if (cfg.indexedFields.empty() && cfg.compositeUniques.empty()) continue;
- try {
- const auto rc = resolveCollection(qualified);
- auto* ds = docStore(rc.project);
- auto* lmdb =
- dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
- if (lmdb == nullptr) continue;
- // v2.17.0 - an index over a field stored encrypted indexes
- // ciphertext under random IVs: lookups never hit and a unique
- // constraint never fires. Such declarations are disarmed (neither
- // maintained nor consulted) and named, so the operator drops them.
- CollectionCfg armed = cfg;
- if (encryption_ && encryption_->isEnabled()) {
- const EncryptionRule rule = encryptionRuleFor(qualified);
- const auto enc = [&](const std::string& f) {
- return !isReservedField(f) && encryption_->isEncryptedPath(f, rule);
- };
- const auto strip = [&](std::vector<std::string>& v, const char* what) {
- for (auto it = v.begin(); it != v.end();) {
- if (enc(*it)) {
- spdlog::error("v2.17 encryption: {} on {}#{} is DISARMED - the field is "
- "stored encrypted. Drop it.", what, qualified, *it);
- it = v.erase(it);
- } else {
- ++it;
- }
- }
- };
- strip(armed.indexedFields, "index");
- strip(armed.uniqueFields, "unique constraint");
- for (auto it = armed.compositeUniques.begin(); it != armed.compositeUniques.end();) {
- if (std::any_of(it->begin(), it->end(), enc)) {
- spdlog::error("v2.17 encryption: a composite unique constraint on {} is "
- "DISARMED - one of its fields is stored encrypted. Drop it.",
- qualified);
- it = armed.compositeUniques.erase(it);
- } else {
- ++it;
- }
- }
- }
- lmdb->set_indexed_fields(rc.collection, armed.indexedFields);
- // v2.11.0 T11 — arm uniqueFields the same way. This is the fix
- // for the exact failure mode the type was built to avoid:
- // uniqueFields has been persisted since T8 with no RPC or proto
- // surface, which was safe (nothing consulted it); now that
- // set_unique_fields is reachable, a restart that skipped this
- // call would silently stop enforcing a constraint every write
- // handler still advertises as active.
- lmdb->set_unique_fields(rc.collection, armed.uniqueFields);
- // v2.12.0 - composite constraints, armed the same way and for the
- // same reason: skipping this would stop enforcing a constraint the
- // record still declares. Self-healed below if its sub-db is gone.
- lmdb->set_composite_uniques(rc.collection, armed.compositeUniques);
- for (const auto& cf : armed.compositeUniques) {
- if (lmdb->has_composite_unique_subdb(rc.collection, cf)) continue;
- uint64_t rows = 0;
- auto dupes = lmdb->build_composite_unique(rc.collection, cf, rows);
- if (dupes.empty()) {
- spdlog::warn("v2.12 composite unique: rebuilt {}#({}) over {} row(s) - "
- "declared but its sub-db was absent",
- qualified, smartbotic::db::storage::composite_display_name(cf), rows);
- } else {
- // Cannot happen through the API (declaring over duplicates is
- // refused). If it does, say so loudly: the constraint stays
- // declared and armed, but rows already violating it exist.
- spdlog::error("v2.12 composite unique: {}#({}) is declared but {} "
- "existing value combination(s) violate it (e.g. document "
- "'{}'); its index could not be rebuilt. Writes that would "
- "add another duplicate are still refused.",
- qualified, smartbotic::db::storage::composite_display_name(cf),
- dupes.size(), dupes.front().sample_id);
- }
- }
- ++applied;
- spdlog::info("v2.9 index: {} field(s) active on {} ({} unique)",
- cfg.indexedFields.size(), qualified, cfg.uniqueFields.size());
- // Self-heal a declared index whose sub-db is absent. That happens
- // when the KEY FORMAT VERSION in the sub-db prefix changes (v2.9.1
- // unified the numeric encoding, so `_idx_` became `_idx2_`), and it
- // would otherwise leave the declaration pointing at nothing: writes
- // would maintain the new index correctly, but rows written BEFORE the
- // upgrade would have no postings, so an indexed query would silently
- // return only the newer ones. Rebuilding is the only safe reading.
- for (const auto& field : armed.indexedFields) {
- if (lmdb->index_stats(rc.collection, field).has_value()) continue;
- const uint64_t rows = lmdb->build_index(rc.collection, field);
- spdlog::warn("v2.9 index: rebuilt {}#{} over {} row(s) - the index "
- "was declared but its sub-db was absent (key format "
- "change or a manual removal)",
- qualified, field, rows);
- }
- } catch (const std::exception& e) {
- // Advisory per collection: one unparseable name must not stop the
- // rest from being armed. Loud, because a missing declaration means
- // that collection's index silently stops being maintained.
- spdlog::error("v2.9 index: could not apply declarations for {}: {}",
- qualified, e.what());
- }
- }
- if (applied > 0) {
- spdlog::info("v2.9 index: applied declarations for {} collection(s)", applied);
- }
- }
- MemoryStore::TtlExpiryAction DatabaseService::ttlExpiryRelationDecision(
- const std::string& qualifiedCollection, const std::string& id, bool firstAttempt) {
- using Action = MemoryStore::TtlExpiryAction;
- // Thin binder over relations/relation_cascade.cpp's ttlExpiryDecision() -
- // the policy itself lives there so it is unit-testable against the same
- // fixtures the cascade tests use, without a DatabaseService. All this does
- // is resolve the per-project LMDB store and supply the replication/events
- // notifier.
- if (!relation_manager_ || !config_manager_ || !store_ || !persistence_) {
- return Action::Proceed;
- }
- if (qualifiedCollection.empty() || qualifiedCollection[0] == '_') return Action::Proceed;
- try {
- const auto rc = resolveCollection(qualifiedCollection);
- auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
- docStore(rc.project));
- // No LMDB substrate means no reverse index to consult, so the
- // pre-v2.11.0 behaviour is all that is available.
- if (lmdb == nullptr) return Action::Proceed;
- // Replication + Subscribe events, driven per mutation - the same wiring
- // DatabaseGrpcImpl::performRelationCascade() uses. Without it a
- // TTL-driven cascade would be invisible to followers and subscribers,
- // and a follower that never saw the child deletions diverges
- // permanently (the v2.3.1 class of bug).
- // v2.12.0 - an expiry has no caller, so every event this cascade
- // produces carries an explicitly EMPTY actor. Letting it default
- // would report a nulled child's previous writer as the cause.
- auto notify = [this](const std::string& coll, const std::string& docId,
- const std::optional<Document>& doc, EventType eventType) {
- notifyReplicationAndEvents(coll, docId, doc, eventType, std::string{});
- };
- // firstAttempt -> the refusal (if any) is logged at WARN; a retry of an
- // already-reported document logs at DEBUG. The sweeper owns that
- // decision because it is the only thing that knows the document has
- // been refused before.
- return smartbotic::database::ttlExpiryDecision(
- *relation_manager_, *lmdb, *persistence_, *store_, *config_manager_,
- qualifiedCollection, id, notify, firstAttempt);
- } catch (const std::exception& e) {
- // Never expire a parent whose children could not be evaluated.
- spdlog::error("TTL expiry of '{}/{}': could not resolve its storage ({}) - the "
- "document is left in place and will be retried",
- qualifiedCollection, id, e.what());
- return Action::Skip;
- }
- }
- void DatabaseService::applyRelationDeclarations(bool afterMigrations) {
- // Group by (project, bare child collection) — set_relations() is a
- // per-collection call on that project's LmdbDocumentStore and replaces
- // whatever was declared before, so every relation sharing a child
- // collection must land in one call.
- std::unordered_map<std::string,
- std::vector<smartbotic::db::storage::RelationRef>> byChild;
- // Track which project each grouping key belongs to alongside the bare
- // collection name, since the map key alone doesn't carry it.
- std::unordered_map<std::string, std::pair<std::string, std::string>> keyToProjectCollection;
- for (const auto& r : relation_manager_->listRelations()) {
- try {
- const auto rn = resolveCollection(r.name);
- const auto rc = resolveCollection(r.child);
- // v2.11.0 T13 — parent resolved to its bare name, same reasoning
- // as armRelationsForChild's mirror of this construction.
- const auto pc = resolveCollection(r.parent);
- const std::string key = rc.project + ":" + rc.collection;
- // v2.11.0 T13 round 2 — snapshot relationsEnforced at boot-time
- // arming, same reasoning as armRelationsForChild's mirror of
- // this construction. `key` is already the qualified child name
- // configFor expects.
- const bool enforced = config_manager_->configFor(key).relationsEnforced;
- byChild[key].push_back(smartbotic::db::storage::RelationRef{
- rn.collection, r.childField, pc.collection, r.validateOnWrite, enforced});
- keyToProjectCollection[key] = {rc.project, rc.collection};
- } catch (const std::exception& e) {
- // Advisory per relation: one unparseable declaration must not
- // stop the rest from being armed. Loud, because a skipped
- // relation silently maintains no reverse index for its child.
- spdlog::error("v2.11 relations: could not apply declaration '{}': {}",
- r.name, e.what());
- }
- }
- size_t applied = 0;
- for (const auto& [key, refs] : byChild) {
- const auto& [project, collection] = keyToProjectCollection[key];
- try {
- // ⚠ v2.11.0 close-out — getOrCreate, not get(), on the POST-MIGRATION
- // pass. docStore() is projects_->get(), which does NOT create an env,
- // and a `create_relation` migration in a project that has never been
- // written to has no env yet: the declaration persisted, this pass
- // skipped it, and the relation maintained no reverse index and
- // enforced NOTHING until the next restart - the exact
- // "declared but not enforcing" state the op was added to avoid, just
- // narrowed to new projects. A migration declaring a relation IS a
- // statement that the project exists, and the mirror resolver would
- // getOrCreate the same env on the first write anyway.
- //
- // The BOOT pass deliberately keeps get(): creating envs there would
- // resurrect the env of a project whose declarations are merely stale.
- auto* ds = (afterMigrations && projects_)
- ? projects_->getOrCreate(project)
- : docStore(project);
- auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
- if (lmdb == nullptr) continue;
- lmdb->set_relations(collection, refs);
- ++applied;
- spdlog::info("v2.11 relations: {} relation(s) active with child '{}:{}'",
- refs.size(), project, collection);
- // v2.11.0 T7 self-heal — mirrors applyIndexDeclarations()'s
- // rebuild of a declared-but-absent index sub-db, for the same
- // reason: a relation whose reverse index sub-db is missing is
- // exactly the "declared but not enforcing" bug this task exists
- // to close. Reachable paths that leave a relation in this state:
- // a snapshot/backup restored from before the sub-db existed, or
- // an operator manually dropping the `_relidx1_*` sub-db (there
- // is no dropRelation-only-the-index tool). CreateRelation's own
- // bootstrap scan (see database_grpc_impl.cpp) covers the normal
- // declare-time path; this covers everything else.
- //
- // ⚠ v2.11.0 close-out (review minor 2) — the SAME code path is the
- // NORMAL, expected one for a relation a migration just declared:
- // migrations run after this pass, so runMigrations() calls it again
- // and the brand-new relation legitimately has no sub-db yet. Logging
- // "declared but its sub-db was absent (restored snapshot or a manual
- // removal)" at WARN there describes a fault that did not happen.
- // `afterMigrations` distinguishes the two so the text and the level
- // match the event.
- for (const auto& ref : refs) {
- if (lmdb->relation_index_exists(ref.name)) continue;
- const uint64_t rows =
- lmdb->build_relation_index(ref.name, collection, ref.childField);
- if (afterMigrations) {
- spdlog::info("v2.11 relations: built the reverse index for '{}' over {} "
- "existing row(s) in '{}:{}' - a migration declared this "
- "relation on this boot",
- ref.name, rows, project, collection);
- } else {
- spdlog::warn("v2.11 relations: rebuilt '{}' over {} row(s) in '{}:{}' - the "
- "relation was declared but its reverse index sub-db was absent "
- "(restored snapshot predating it, or a manual removal)",
- ref.name, rows, project, collection);
- }
- }
- } catch (const std::exception& e) {
- spdlog::error("v2.11 relations: could not apply declarations for '{}:{}': {}",
- project, collection, e.what());
- }
- }
- if (applied > 0) {
- spdlog::info("v2.11 relations: applied declarations for {} child collection(s)", applied);
- }
- }
- void DatabaseService::auditSubdbPlacement() {
- if (!projects_) return;
- for (const auto& name : projects_->listOpen()) {
- auto h = projects_->getHandle(name);
- if (!h.env) continue;
- try {
- // audit_env(), NOT audit(). The path-taking overload opens a
- // second MDB_env on the same file; closing it would drop the
- // POSIX record locks this process already holds for `h.env`
- // (POSIX locks are per-process, and closing any fd on a file
- // releases all of them), leaving every later mdb_txn_begin
- // failing EINVAL. Borrow the open handle instead.
- const auto rep = smartbotic::db::storage::audit_env(h.env->raw(), name);
- if (rep.misplaced.empty()) {
- spdlog::debug("placement audit: project '{}' consistent ({} rows)",
- name, rep.rows_scanned);
- continue;
- }
- // Summarise per (physical -> declared home) pair; one line per
- // affected document would be unreadable at scale.
- std::map<std::string, uint64_t> pairs;
- for (const auto& m : rep.misplaced) {
- ++pairs[m.physical_subdb + " -> " + m.home_subdb];
- }
- spdlog::error("placement audit: project '{}' has {} document(s) in the "
- "wrong sub-db. Reads served from LMDB will not find them "
- "under their own collection. Repair offline with: "
- "smartbotic-db-cli reconcile-subdbs --env {} --project {} --apply",
- name, rep.misplaced.size(), h.env->path(), name);
- for (const auto& [pair, count] : pairs) {
- spdlog::error("placement audit: {} document(s) {}", count, pair);
- }
- } catch (const std::exception& e) {
- // Advisory only — a failed audit must not take the service down.
- spdlog::warn("placement audit: project '{}' could not be audited: {}",
- name, e.what());
- }
- }
- }
- 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
- // name; both resolve to one sub-db, so both count as "in memory".
- std::map<std::string, std::vector<std::string>> memNames;
- for (const auto& name : store_->listCollections()) {
- try {
- auto rc = sd::resolveCollection(name);
- if (rc.collection.empty() || rc.collection.front() == '_') continue;
- memNames[rc.qualified].push_back(name);
- } catch (const std::exception&) {
- continue; // a malformed legacy key; the backfill already reported it
- }
- }
- const auto samples = [](const std::vector<std::string>& ids) {
- std::string out;
- for (size_t i = 0; i < ids.size() && i < 10; ++i) {
- if (i) out += ", ";
- out += ids[i];
- }
- 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;
- uint64_t notAdoptable = 0; // disk-only rows whose collection exists only on disk
- for (const auto& project : projects_->listOpen()) {
- auto* ds = docStore(project);
- if (!ds) continue;
- std::set<std::string> collections;
- try {
- for (auto& c : ds->list_collections()) collections.insert(std::move(c));
- } catch (const std::exception& e) {
- spdlog::warn("key audit: project '{}' could not be listed: {}", project, e.what());
- continue;
- }
- const std::string prefix = project + sd::kProjectSeparator;
- for (const auto& [qualified, names] : memNames) {
- if (qualified.rfind(prefix, 0) == 0) collections.insert(qualified.substr(prefix.size()));
- }
- for (const auto& coll : collections) {
- if (coll.empty() || coll.front() == '_') continue;
- const std::string qualified = prefix + coll;
- try {
- auto disk = ds->list_ids(coll);
- if (!disk) continue; // backend cannot list
- // 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::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;
- 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();
- // 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, /*quiet=*/true) ? 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();
- // Counted under every policy, so `report` can price `adopt`
- // before anything acts (asked by smartbotic-vectorapi).
- if (!inMemory) notAdoptable += diskOnly.size();
- const std::string action =
- diskPolicy == "report"
- ? (inMemory ? "reported (adopt would load them)"
- : "reported (not adoptable: the collection exists only on disk)") :
- (diskPolicy == "adopt" && !inMemory)
- ? "reported (not adoptable: the collection exists only on disk)" :
- diskPolicy == "adopt" ? "adopted into memory (loaded unchanged)" : "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}, {"collection_in_memory", inMemory},
- {"ids", diskOnly}, {"failed", failed}};
- }
- if (!memOnly.empty()) {
- memOnlyTotal += memOnly.size();
- 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());
- }
- }
- }
- 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["adopted"] = adopted;
- report["not_adoptable"] = notAdoptable;
- 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::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, {} "
- "not adoptable (their collection exists only on disk; counted under any "
- "policy), {} 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, notAdoptable, diskRemoved, written, memRemoved, actionFailed);
- }
- }
- bool DatabaseService::backfillIntoDocStore() {
- if (!projects_) {
- // Registry open failed earlier; nothing to back-fill into.
- return true;
- }
- // v2.3 — MemoryStore stores collection keys in qualified form
- // ("project:collection"). For the default project (back-compat
- // path) the marker check operates on the default env. Skip when
- // already migrated.
- auto handle = projects_->getHandle(smartbotic::database::kDefaultProject);
- if (handle.env) {
- try {
- if (smartbotic::db::storage::migration_complete(*handle.env)) {
- spdlog::info("v2.3 backfill: default project already migrated, skipping");
- return true;
- }
- } catch (const std::exception& e) {
- spdlog::warn("v2.3 backfill: migration_complete probe failed: {} — "
- "treating default env as fresh and proceeding",
- e.what());
- }
- }
- const auto collections = store_->listCollections();
- uint64_t total_docs = 0;
- uint64_t total_failures = 0;
- auto t0 = std::chrono::steady_clock::now();
- for (const auto& qualified : collections) {
- if (qualified.empty() || qualified[0] == '_') continue;
- // Each qualified key parses to (project, collection); route the
- // mirror write to the right project's env.
- smartbotic::database::ProjectCollection pc;
- try {
- pc = smartbotic::database::parseProjectCollection(qualified);
- } catch (const std::exception&) {
- // Legacy unqualified key — treat as default project.
- pc = {std::string(smartbotic::database::kDefaultProject), qualified};
- }
- auto* ds = projects_->getOrCreate(pc.project);
- if (!ds) {
- ++total_failures;
- continue;
- }
- const auto docs = store_->getAllDocuments(qualified);
- for (const auto& doc : docs) {
- std::optional<Document> opt_doc(doc);
- const uint64_t drift_before = mirror_drift_count_.load(std::memory_order_relaxed);
- // v2.11.0 T13 round 2 — UniqueViolation/MissingParentReference are
- // rethrown UNCAUGHT by applyDualWriteMirror (deliberately - see
- // both exceptions' header comments), unlike a genuine mirror
- // fault which is swallowed and only shows up as a drift bump
- // below. Uncaught here would escape this loop, backfillIntoDocStore
- // and initialize() itself, refusing startup over one rejected row.
- // Practically unreachable today - backfill only runs migrating a
- // v1.x dataset, which predates both `_relations` and unique-index
- // declarations - but catching removes that reasoning burden for
- // the next reader, same as any other row here that fails.
- try {
- smartbotic::db::storage::applyDualWriteMirror(
- ds, mirror_healthy_, mirror_drift_count_,
- pc.collection, doc.id, opt_doc, EventType::INSERT);
- } catch (const std::exception& e) {
- spdlog::error("v2.3 backfill: mirror rejected {}/{}: {} - row stays "
- "in MemoryStore only, LMDB does not have it",
- qualified, doc.id, e.what());
- ++total_failures;
- }
- 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) {
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- const std::string status = "STATUS=v2.3 backfill: " +
- std::to_string(total_docs) + " docs mirrored";
- sd_notify(0, status.c_str());
- spdlog::info("v2.3 backfill: {} docs mirrored ({} failures so far)",
- total_docs, total_failures);
- }
- }
- }
- const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::steady_clock::now() - t0).count();
- if (total_failures == 0) {
- // Stamp schema_version=2 on every opened project env. Subsequent
- // boots short-circuit at migration_complete().
- for (const auto& name : projects_->listOpen()) {
- auto h = projects_->getHandle(name);
- if (!h.env) continue;
- try {
- smartbotic::db::storage::mark_migration_complete(*h.env);
- } catch (const std::exception& e) {
- spdlog::warn("v2.3 backfill: schema_version marker write failed for "
- "project '{}': {}", name, e.what());
- }
- }
- spdlog::info("v2.3 backfill: complete — {} docs across {} collections in {} ms",
- total_docs, collections.size(), elapsed);
- } else {
- spdlog::error("v2.3 backfill: completed with {} failures out of {} docs "
- "in {} ms — mirror_healthy_=false, reads must NOT flip to LMDB",
- total_failures, total_docs, elapsed);
- }
- return true;
- }
- void DatabaseService::start() {
- if (running_.exchange(true)) {
- return;
- }
- spdlog::info("Starting database service with {} listener(s)", config_.listeners.size());
- // Start components
- store_->start();
- persistence_->start();
- events_->start();
- files_->start();
- if (config_.replicationEnabled) {
- replication_->start();
- // Set initial local collections for discovery
- replication_->setLocalCollections(store_->listCollections());
- }
- // Start gRPC server
- startGrpcServer();
- spdlog::info("Database service started");
- }
- void DatabaseService::stop() {
- if (!running_.exchange(false)) {
- return;
- }
- spdlog::info("Stopping database service...");
- // Stop gRPC server first
- stopGrpcServer();
- // Stop components in reverse order
- if (replication_) {
- replication_->stop();
- }
- if (files_) {
- files_->stop();
- }
- if (events_) {
- events_->stop();
- }
- if (persistence_ && store_) {
- // v1.8.0 — take a final snapshot on graceful shutdown so the next
- // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
- // replay" which trips auto-readonly mode. This makes ordinary
- // restarts pass through cleanly without needing
- // `smartbotic-db-cli unlock`.
- //
- // v1.8.2 — extend systemd's stop watchdog before doing it. On Zoe
- // (1.85M docs / ~5 GB tracked) the serialize takes ~70 s and the
- // default TimeoutStopSec=30s SIGKILLed the process mid-write, peak
- // RSS hit 11 GB (live state + uncompressed serialize buffer), and
- // the new snapshot never made it to disk anyway. EXTEND_TIMEOUT_USEC
- // tells systemd we're working — same protocol the recovery path
- // uses during startup. Paired with TimeoutStopSec=300 in the unit
- // file as the static cap.
- #ifdef HAVE_SYSTEMD
- sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
- sd_notify(0, "STATUS=Writing final snapshot");
- #endif
- try {
- persistence_->forceSnapshot(*store_);
- spdlog::info("Final snapshot taken on shutdown");
- } catch (const std::exception& e) {
- spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
- "boot may be WAL-only and trip auto-readonly mode", e.what());
- }
- }
- if (persistence_) {
- persistence_->stop();
- }
- if (store_) {
- store_->stop();
- }
- spdlog::info("Database service stopped");
- }
- void DatabaseService::wait() {
- if (serverThread_.joinable()) {
- serverThread_.join();
- }
- }
- void DatabaseService::signalStop() {
- stopRequested_ = true;
- stop();
- }
- nlohmann::json DatabaseService::getStats() const {
- nlohmann::json stats;
- if (store_) {
- auto storeStats = store_->getStats();
- stats["documents"] = storeStats.totalDocuments;
- stats["collections"] = storeStats.totalCollections;
- stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
- stats["inserts"] = storeStats.insertCount;
- stats["updates"] = storeStats.updateCount;
- stats["deletes"] = storeStats.deleteCount;
- stats["queries"] = storeStats.queryCount;
- }
- if (persistence_) {
- auto persistStats = persistence_->getStats();
- stats["wal_sequence"] = persistStats.walSequence;
- stats["wal_size_bytes"] = persistStats.walSizeBytes;
- stats["snapshot_count"] = persistStats.snapshotCount;
- stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
- }
- if (events_) {
- stats["subscriptions"] = events_->subscriptionCount();
- }
- return stats;
- }
- DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
- std::ifstream file(configPath);
- if (!file) {
- throw std::runtime_error("Failed to open config file: " + configPath.string());
- }
- nlohmann::json json;
- file >> json;
- return parseConfig(json);
- }
- DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
- Config config;
- // Check for both "storage" and "database" keys for backward compatibility
- const nlohmann::json* dbConfig = nullptr;
- if (json.contains("database")) {
- dbConfig = &json["database"];
- } else if (json.contains("storage")) {
- dbConfig = &json["storage"];
- }
- if (dbConfig) {
- const auto& db = *dbConfig;
- config.nodeId = db.value("node_id", config.nodeId);
- 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.
- if (db.contains("listeners") && db["listeners"].is_array()) {
- for (const auto& l : db["listeners"]) {
- ListenerConfig lc;
- lc.bind = l.value("bind", lc.bind);
- lc.port = l.value("port", lc.port);
- if (l.contains("tls") && l["tls"].is_object()) {
- const auto& t = l["tls"];
- lc.tls.enabled = t.value("enabled", false);
- lc.tls.cert_path = t.value("cert_path", std::string{});
- lc.tls.key_path = t.value("key_path", std::string{});
- lc.tls.auto_self_signed_if_missing =
- t.value("auto_self_signed_if_missing", true);
- }
- if (l.contains("auth") && l["auth"].is_object()) {
- const auto& a = l["auth"];
- lc.auth.required = a.value("required", false);
- if (a.contains("keys") && a["keys"].is_array()) {
- for (const auto& k : a["keys"]) {
- // v2.7.0 — a key is either a bare token (v2.4-v2.6
- // shape) or {"name","key"}. The name becomes the
- // principal that policy is written against; a bare
- // token maps to the reserved `unnamed`, so old
- // configs keep authenticating but cannot be told
- // apart in a policy until they are named.
- if (k.is_string()) {
- lc.auth.keys.push_back(
- {smartbotic::database::auth::kPrincipalUnnamed,
- k.get<std::string>()});
- } else if (k.is_object()) {
- const std::string name = k.value("name", std::string{});
- const std::string key = k.value("key", std::string{});
- if (key.empty()) {
- spdlog::warn("auth: listener {}:{} has a key entry "
- "with no `key` value - skipped",
- lc.bind, lc.port);
- continue;
- }
- lc.auth.keys.push_back(
- {name.empty()
- ? std::string(smartbotic::database::auth::kPrincipalUnnamed)
- : name,
- key});
- }
- }
- }
- }
- config.listeners.push_back(std::move(lc));
- }
- }
- // Expand environment variables in data directory
- std::string dataDir = db.value("data_directory", "");
- if (dataDir.find("${HOME}") != std::string::npos) {
- const char* home = std::getenv("HOME");
- if (home) {
- size_t pos = dataDir.find("${HOME}");
- dataDir.replace(pos, 7, home);
- }
- }
- config.dataDirectory = dataDir;
- // Migrations settings
- if (db.contains("migrations")) {
- auto& migrations = db["migrations"];
- config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
- config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
- config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
- std::string migDir = migrations.value("directory", "");
- if (migDir.find("${HOME}") != std::string::npos) {
- const char* home = std::getenv("HOME");
- if (home) {
- size_t pos = migDir.find("${HOME}");
- migDir.replace(pos, 7, home);
- }
- }
- config.migrations.directory = migDir;
- }
- // Memory eviction settings
- if (db.contains("memory")) {
- auto& memory = db["memory"];
- // No deprecation warning (removed after 2.21.2). From v2.0 these
- // keys logged "deprecated and will be removed in v2.1" at every
- // boot. They were never removed and no removal is planned: they set
- // MemoryStore's budget, eviction and pressure levels, and emergency
- // pressure refuses writes, so they are live controls (and since
- // 2.21.2 the budget covers vectors too). The warning read as stale
- // output from a 2.0 build and invited an operator to delete the
- // budget. MemoryStore goes, and these keys with it, only when the
- // write-handler migration lands (docs/ROADMAP.md, "Pending").
- config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
- config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
- config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
- config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
- // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
- config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
- config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
- config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
- config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
- config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
- config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
- config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
- // v1.7.0 T10 — eviction burst event threshold
- config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
- // v2.4.3 — eviction drain cap (0 disables)
- config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
- }
- // v2.11.0 close-out — TTL sweep budgets. Its own block rather than
- // `memory`, because these bound expiry work per sweep, not memory.
- if (db.contains("ttl")) {
- auto& ttl = db["ttl"];
- config.ttlMaxCandidatesPerSweep =
- ttl.value("max_candidates_per_sweep", config.ttlMaxCandidatesPerSweep);
- config.ttlMaxBlockedRetriesPerSweep =
- ttl.value("max_blocked_retries_per_sweep", config.ttlMaxBlockedRetriesPerSweep);
- config.ttlBlockedRetrySweeps =
- ttl.value("blocked_retry_sweeps", config.ttlBlockedRetrySweeps);
- config.ttlBlockedSummarySweeps =
- ttl.value("blocked_summary_sweeps", config.ttlBlockedSummarySweeps);
- }
- // Persistence settings
- if (db.contains("persistence")) {
- auto& persistence = db["persistence"];
- config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
- config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
- config.compressionEnabled = persistence.value("compression", "lz4") != "none";
- // Snapshot durability (NEW in v1.6.1)
- if (persistence.contains("snapshots")) {
- const auto& snap = persistence["snapshots"];
- config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
- config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
- }
- // Recovery (NEW in v1.6.1)
- if (persistence.contains("recovery")) {
- const auto& rec = persistence["recovery"];
- std::string modeStr = rec.value("mode", std::string("normal"));
- try {
- config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
- } catch (const std::exception& e) {
- spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
- modeStr, e.what());
- config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
- }
- config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
- config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
- }
- }
- // File settings
- if (db.contains("files")) {
- auto& files = db["files"];
- config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
- // v2.8.0 — this interval now drives the file EXPIRY sweep as well
- // as orphan cleanup, so accept the plainer name too. The original
- // key kept working; nothing read either of them before 2.8.0
- // because there was no sweeper thread at all.
- config.fileCleanupIntervalSec =
- files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
- config.fileCleanupIntervalSec =
- files.value("cleanup_interval_sec", config.fileCleanupIntervalSec);
- // v2.8.0 — default retention per file type. The analogue of a
- // collection's defaultTtlSeconds, so retention is an operator
- // setting rather than something every uploader must remember.
- //
- // "default_ttl_seconds": {
- // "acme:generated": 86400, // one project, one type
- // "generated": 604800, // any project
- // "acme:*": 2592000, // every type in one project
- // "*": 0 // everything (0 = keep)
- // }
- if (files.contains("default_ttl_seconds") &&
- files["default_ttl_seconds"].is_object()) {
- for (const auto& [k, v] : files["default_ttl_seconds"].items()) {
- if (v.is_number_unsigned()) {
- config.fileDefaultTtlByType[k] = v.get<uint32_t>();
- }
- }
- }
- if (files.contains("allowed_types")) {
- for (const auto& type : files["allowed_types"]) {
- config.allowedFileTypes.push_back(type.get<std::string>());
- }
- }
- }
- // Encryption settings
- if (db.contains("encryption")) {
- auto& encryption = db["encryption"];
- config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
- config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
- std::string keyFile = encryption.value("key_file", "");
- if (keyFile.find("${HOME}") != std::string::npos) {
- const char* home = std::getenv("HOME");
- if (home) {
- size_t pos = keyFile.find("${HOME}");
- keyFile.replace(pos, 7, home);
- }
- }
- config.keyFilePath = keyFile;
- }
- // Replication settings
- if (db.contains("replication")) {
- auto& replication = db["replication"];
- config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
- config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
- if (replication.contains("peers")) {
- for (const auto& peer : replication["peers"]) {
- config.peerAddresses.push_back(peer.get<std::string>());
- }
- }
- }
- // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
- if (db.contains("grpc")) {
- const auto& grpc = db["grpc"];
- config.grpc.maxReceiveMessageSizeMb =
- grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
- config.grpc.maxSendMessageSizeMb =
- grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
- config.grpc.resourceQuotaMemoryMb =
- grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
- config.grpc.maxConcurrentSubscribeStreams =
- grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
- config.grpc.maxConcurrentFileStreams =
- grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
- }
- }
- // v2.4 back-compat shim. If no listeners[] was provided, synthesize
- // one from the legacy bind_address + rpc_port fields. This is what
- // every existing v2.3 deployment will hit on first v2.4 boot —
- // their configs don't know about listeners[] yet, and they get
- // exactly the same listener they had before.
- if (config.listeners.empty()) {
- ListenerConfig legacy;
- legacy.bind = config.bindAddress;
- legacy.port = config.rpcPort;
- legacy.tls.enabled = false;
- legacy.auth.required = false;
- config.listeners.push_back(std::move(legacy));
- }
- return config;
- }
- void DatabaseService::setupComponents() {
- // v2.3 multi-project storage substrate.
- //
- // Each project lives at `<dataDir>/projects/<name>/env/`. The default
- // project always exists and is what v2.0-v2.2 clients (which don't
- // address projects) implicitly use.
- //
- // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
- // path. migrateLegacyEnvToDefaultProject() detects that layout and
- // atomically moves it under `projects/default/env/` before the
- // registry opens.
- migrateLegacyEnvToDefaultProject();
- try {
- constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
- constexpr uint32_t kMaxDbs = 1024;
- projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
- config_.dataDirectory / "projects", kMapSize, kMaxDbs);
- const auto opened = projects_->openExisting();
- spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
- opened.size(),
- [&opened]() {
- std::string s;
- for (size_t i = 0; i < opened.size(); ++i) {
- if (i) s += ", ";
- s += opened[i];
- }
- return s;
- }());
- } catch (const std::exception& e) {
- spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
- "service cannot start without LMDB; bailing",
- (config_.dataDirectory / "projects").string(), e.what());
- projects_.reset();
- throw;
- }
- // Create memory store with eviction config
- MemoryStore::Config storeConfig;
- storeConfig.nodeId = config_.nodeId;
- storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
- storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
- storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
- storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
- // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
- storeConfig.evictionChunkSize = config_.evictionChunkSize;
- storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
- storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
- storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
- storeConfig.memorySoftPercent = config_.memorySoftPercent;
- storeConfig.memoryHardPercent = config_.memoryHardPercent;
- storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
- storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
- storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
- // v2.11.0 close-out — TTL sweep budgets (storage.ttl).
- storeConfig.ttlMaxCandidatesPerSweep = config_.ttlMaxCandidatesPerSweep;
- storeConfig.ttlMaxBlockedRetriesPerSweep = config_.ttlMaxBlockedRetriesPerSweep;
- storeConfig.ttlBlockedRetrySweeps = config_.ttlBlockedRetrySweeps;
- storeConfig.ttlBlockedSummarySweeps = config_.ttlBlockedSummarySweeps;
- store_ = std::make_unique<MemoryStore>(storeConfig);
- // Create view manager (cache loaded in initialize() after persistence recovery)
- view_manager_ = std::make_unique<ViewManager>(*store_);
- // Create per-collection config manager and attach it to the store so the
- // write paths route document timestamp stamps through it.
- config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
- // v2.8.0 — access policy. Constructed here; its cache is loaded after
- // recovery alongside the view and collection-config caches.
- policy_manager_ = std::make_unique<PolicyManager>(*store_);
- // v2.11.0 T6a — relation declarations. Constructed here; its cache is
- // loaded after recovery alongside the view/config/policy caches.
- relation_manager_ = std::make_unique<RelationManager>(*store_);
- store_->setConfigManager(config_manager_.get());
- // v1.9.0 — disk-resident version history. Replaces the in-heap
- // `CollectionData::versionHistory` deques that were the dominant
- // source of the Zoe untracked-RSS gap. One file per collection at
- // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
- // here, wired into the store immediately so snapshot deserializer
- // can migrate pre-v1.9 in-memory history blocks straight to disk.
- HistoryStore::Config histConfig;
- histConfig.dataDir = config_.dataDirectory;
- history_store_ = std::make_unique<HistoryStore>(histConfig);
- store_->setHistoryStore(history_store_.get());
- // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
- // resolver. Every write that flows through store_ commits to the
- // right per-project LMDB env BEFORE the per-collection lock releases.
- if (projects_) {
- auto* registry = projects_.get();
- store_->setDocumentStoreMirror(
- [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
- return registry->getOrCreate(project);
- },
- &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
- // caller (config loader / CLI parser) has already populated — including
- // recoveryMode — and overlay the top-level convenience fields.
- PersistenceManager::Config persistConfig = config_.persistenceConfig;
- persistConfig.dataDir = config_.dataDirectory;
- persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
- persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
- persistConfig.compressionEnabled = config_.compressionEnabled;
- persistConfig.nodeId = config_.nodeId;
- // Mirror the resolved recoveryMode back into our Config so downstream code
- // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
- // without having to reach into the PersistenceManager.
- config_.persistenceConfig = persistConfig;
- persistence_ = std::make_unique<PersistenceManager>(persistConfig);
- // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
- store_->setPersistCallback([this](const std::string& collection, const std::string& id,
- const std::optional<Document>& doc, EventType eventType,
- const std::optional<std::string>& actor) {
- // Log to WAL based on event type. v1.7.4: capture the assigned WAL
- // sequence and record it on the store so eviction stubs can carry
- // a real seq (instead of doc.version, which was useless as a
- // `fromSequence` hint and forced a full WAL scan on every fault).
- uint64_t walSeq = 0;
- switch (eventType) {
- case EventType::INSERT:
- if (doc) walSeq = persistence_->logInsert(collection, *doc);
- break;
- case EventType::UPDATE:
- if (doc) walSeq = persistence_->logUpdate(collection, *doc);
- break;
- case EventType::DELETE:
- persistence_->logDelete(collection, id);
- break;
- default:
- break;
- }
- if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
- store_->recordWalSequence(collection, id, walSeq);
- }
- // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
- // that it runs UNDER the per-collection write lock. That closes the
- // race window where readers could see a doc in MemoryStore but not
- // yet in LMDB. The callback now does only WAL + replication + events.
- // v2.11.0 T12 review (C2) — replication + events extracted into
- // notifyReplicationAndEvents() so relations/relation_cascade.cpp can
- // drive them explicitly too. See that method's doc comment.
- notifyReplicationAndEvents(collection, id, doc, eventType, actor);
- });
- // Set up document load callback for LRU eviction recovery.
- //
- // v1.7.4: walSequence is now a real WAL sequence (set by the persist
- // callback below at append time, not the per-doc version counter).
- // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
- // returns entries with seq >= walSequence — the doc's last write is
- // exactly at walSequence, so the very first hit is the one we want.
- // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
- // that predates v1.7.4), fall back to the full-WAL scan from 0.
- 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);
- });
- // Create encryption manager
- EncryptionManager::Config encryptConfig;
- encryptConfig.enabled = config_.encryptionEnabled;
- encryptConfig.keyFilePath = config_.keyFilePath;
- encryptConfig.autoGenerateKey = config_.autoGenerateKey;
- encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
- // Create event manager
- EventManager::Config eventConfig;
- eventConfig.nodeId = config_.nodeId;
- events_ = std::make_unique<EventManager>(eventConfig);
- // Create file manager
- FileManager::Config fileConfig;
- fileConfig.filesDir = config_.dataDirectory / "files";
- fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
- fileConfig.allowedMimeTypes = config_.allowedFileTypes;
- fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
- fileConfig.defaultTtlSecondsByType = config_.fileDefaultTtlByType;
- files_ = std::make_unique<FileManager>(fileConfig);
- // Create replication manager
- ReplicationManager::Config replConfig;
- replConfig.nodeId = config_.nodeId;
- replConfig.peerAddresses = config_.peerAddresses;
- replConfig.conflictResolution = config_.conflictResolution;
- replication_ = std::make_unique<ReplicationManager>(replConfig);
- // Wire replication entry apply callback
- replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
- applyReplicatedEntry(entry);
- });
- // Create gRPC implementations
- storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
- *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
- *policy_manager_, *relation_manager_
- );
- // v2.7.0 — hand the impl the union of every listener's keys so it can
- // resolve a principal per call. A token is only accepted if some listener's
- // auth processor accepted it, so the union cannot widen authentication; it
- // only names what was already authenticated.
- {
- std::vector<smartbotic::database::auth::PrincipalResolver::NamedKey> all;
- for (const auto& l : config_.listeners) {
- for (const auto& k : l.auth.keys) all.push_back({k.name, k.key});
- }
- storageImpl_->setPrincipalKeys(std::move(all));
- }
- // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
- storageImpl_->setStreamLimits(
- config_.grpc.maxConcurrentSubscribeStreams,
- config_.grpc.maxConcurrentFileStreams);
- storageImpl_->setMaxSendBytes(
- static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024); // v2.13.0
- // v2.13.1 - a stored row must stay readable: the largest body a write may
- // leave behind is the send limit less room for metadata and a vector sent
- // alongside (16 KB at dimension 4096). Enforced on insert/update/upsert/
- // batch bodies and on the RESULT of a patch.
- {
- constexpr size_t kReadMargin = 256 * 1024;
- const size_t send = static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024;
- store_->setMaxDocumentBytes(send > 2 * kReadMargin ? send - kReadMargin : send / 2);
- }
- // v2.16.0 - collection schemas. The check sees the body as the store holds
- // it, so it validates a copy: read metadata and `_vector` removed (neither
- // is a user field), sensitive fields decrypted (a rule about a value must
- // judge the value, not its ciphertext).
- store_->setSchemaCheck([this](const std::string& collection, const nlohmann::json& body) {
- auto entry = schemas_.get(CollectionConfigManager::canonicalKey(collection));
- if (!entry) return;
- const nlohmann::json copy = schemaView(body);
- size_t total = 0;
- auto violations = entry->compiled->validate(copy, 10, &total);
- if (violations.empty()) return;
- const std::string summary = smartbotic::db::schema::summarize(violations, total);
- if (entry->audit) {
- // Rate-limited: an audit run on a busy collection must not flood
- // the log. The counter is exact.
- const uint64_t n = entry->auditViolations.fetch_add(1) + 1;
- if (n <= 20 || (n & (n - 1)) == 0) {
- spdlog::warn("v2.16 schema AUDIT: a write to {} does not conform ({} so far): {}",
- collection, n, summary);
- }
- return;
- }
- entry->refusals.fetch_add(1);
- std::vector<std::string> paths;
- for (const auto& v : violations) paths.push_back(v.path);
- throw SchemaViolation(collection, "schema violation: " + summary, std::move(paths));
- });
- replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
- *store_, *replication_, *persistence_
- );
- }
- void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
- const std::string& id,
- const std::optional<Document>& doc,
- EventType eventType,
- const std::optional<std::string>& actor) {
- // Queue for replication broadcast
- if (replication_ && config_.replicationEnabled) {
- databasepb::ReplicationEntry entry;
- entry.set_collection(collection);
- entry.set_document_id(id);
- // v1.8.0 — stamp our nodeId so peers can attribute the write to
- // its actual origin. Pre-v1.8 broadcasts left this empty, which
- // is now treated by receivers as "legacy / unknown origin".
- entry.set_node_id(config_.nodeId);
- entry.set_global_timestamp(
- std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch()
- ).count());
- switch (eventType) {
- case EventType::INSERT:
- entry.set_op(databasepb::OP_INSERT);
- // Send the full Document envelope (id, collection, data,
- // version, timestamps, encryption state). The follower's
- // applyReplicatedEntry uses Document::fromJson() which
- // expects this envelope — sending only doc->data silently
- // dropped every user field on the other side.
- if (doc) entry.set_data(doc->toJson().dump());
- break;
- case EventType::UPDATE:
- entry.set_op(databasepb::OP_UPDATE);
- if (doc) entry.set_data(doc->toJson().dump());
- break;
- case EventType::DELETE:
- entry.set_op(databasepb::OP_DELETE);
- break;
- default:
- break;
- }
- replication_->queueForReplication(entry);
- }
- // Publish event
- if (events_) {
- DatabaseEvent event;
- event.type = eventType;
- event.collection = collection;
- event.documentId = id;
- event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
- std::chrono::system_clock::now().time_since_epoch()
- ).count();
- event.nodeId = config_.nodeId;
- if (actor) {
- event.actor = *actor;
- } else if (doc) {
- event.actor = doc->updatedBy;
- }
- if (doc) {
- event.data = doc->data();
- }
- events_->publish(event);
- }
- }
- void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
- try {
- // v1.8.0 — also append the replicated entry to the local WAL, tagged
- // with the originating node's id. This is what makes follower-side
- // recovery (eviction → WAL fallback, restart → WAL replay) preserve
- // replicated documents. Echo amplification is prevented by:
- // - GetEntriesSince emitting walEntry.nodeId (not local node id)
- // - SyncProtocol skipping entries whose origin is the peer itself
- // both implemented in the same v1.8.0 cycle.
- const std::string origin = entry.node_id().empty()
- ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
- : entry.node_id();
- switch (entry.op()) {
- case databasepb::OP_INSERT:
- case databasepb::OP_UPDATE:
- case databasepb::OP_UPSERT: {
- if (entry.data().empty()) {
- spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
- return;
- }
- auto json = smartbotic::db::parse_to_nlohmann(entry.data());
- Document doc = Document::fromJson(json);
- doc.id = entry.document_id();
- doc.nodeId = entry.node_id();
- // loadDocument bypasses the persist-and-broadcast callback to avoid
- // re-replicating; we explicitly write to the WAL right after with
- // the origin-aware overload so eviction/WAL recovery still works.
- store_->loadDocument(entry.collection(), doc);
- // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
- // MemoryStore persist callback that normally drives the
- // dual-write mirror; in v2.0-v2.2 the mirror was a side
- // channel and reads still hit MemoryStore, so the bypass
- // was harmless. In v2.3 reads are LMDB-first, so a
- // follower that only filled MemoryStore would return
- // empty Find/Get for every replicated doc. Route the
- // entry through the same project-aware mirror the write
- // handlers use.
- if (projects_) {
- auto pc = smartbotic::database::parseProjectCollection(
- 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_,
- pc.collection, doc.id, opt_doc, EventType::INSERT);
- } catch (const smartbotic::db::storage::UniqueViolation& e) {
- // v2.11.0 T11 finding 1 — deliberate choice, not an
- // accident of the generic catch below. By this
- // point store_->loadDocument() above has ALREADY
- // put the row into MemoryStore (loadDocument
- // bypasses the persist callback specifically to
- // avoid re-replicating), so unlike every
- // client-facing write path there is no "reject the
- // whole operation" available: the origin node
- // already committed this write and every other
- // follower is expected to converge to it too.
- // Undoing loadDocument here would silently diverge
- // this follower's data from the rest of the
- // cluster over a constraint that may not even
- // exist on the origin (this follower could have
- // declared the unique field locally, after the
- // fact — replication carries no guarantee the
- // origin shares this node's config). So
- // MemoryStore keeps the row — it is the true
- // record of what replication decided — and the
- // mirror is marked unhealthy ON PURPOSE: this is
- // exactly the pre-T11 swallow-and-flip outcome,
- // chosen deliberately for this one caller so an
- // operator sees the drift (and LMDB-first reads
- // fall back to MemoryStore, which has the answer)
- // rather than nothing signalling a permanent gap
- // between the two stores.
- spdlog::error(
- "v2.11 replication: unique constraint violated applying "
- "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
- "marking the mirror unhealthy so reads fall back instead "
- "of silently disagreeing with MemoryStore",
- entry.collection(), doc.id, e.what());
- mirror_healthy_.store(false, std::memory_order_release);
- mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
- } catch (const smartbotic::db::storage::MissingParentReference& e) {
- // v2.11.0 T13 — same deliberate swallow-and-flip as
- // the UniqueViolation catch just above, for the same
- // reason: loadDocument() has already committed this
- // row into MemoryStore, the origin already accepted
- // the write, and this follower may not even have the
- // same validate_on_write declaration (or the same
- // parent data) as the origin did at the time it
- // wrote. MemoryStore keeps the row; the mirror is
- // marked unhealthy on purpose so an operator sees
- // the drift and reads fall back to MemoryStore
- // rather than the two stores silently disagreeing.
- spdlog::error(
- "v2.11 replication: validate_on_write rejected applying "
- "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
- "marking the mirror unhealthy so reads fall back instead "
- "of silently disagreeing with MemoryStore",
- entry.collection(), doc.id, e.what());
- mirror_healthy_.store(false, std::memory_order_release);
- mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
- }
- }
- }
- if (persistence_) {
- uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
- ? persistence_->logInsert(entry.collection(), doc, origin)
- : persistence_->logUpdate(entry.collection(), doc, origin);
- if (walSeq > 0) {
- store_->recordWalSequence(entry.collection(), doc.id, walSeq);
- }
- }
- spdlog::trace("Applied replicated {} to {}/{} from {}",
- entry.op() == databasepb::OP_INSERT ? "insert" :
- entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
- entry.collection(), entry.document_id(), entry.node_id());
- break;
- }
- case databasepb::OP_DELETE: {
- store_->remove(entry.collection(), entry.document_id());
- if (persistence_) {
- persistence_->logDelete(entry.collection(), entry.document_id(), origin);
- }
- spdlog::trace("Applied replicated delete to {}/{} from {}",
- entry.collection(), entry.document_id(), entry.node_id());
- break;
- }
- case databasepb::OP_CREATE_COLLECTION: {
- CollectionOptions options;
- store_->createCollection(entry.collection(), options);
- if (persistence_) {
- persistence_->logCreateCollection(entry.collection(), options, origin);
- }
- spdlog::trace("Applied replicated create collection {} from {}",
- entry.collection(), entry.node_id());
- break;
- }
- case databasepb::OP_DROP_COLLECTION: {
- store_->dropCollection(entry.collection());
- if (persistence_) {
- persistence_->logDropCollection(entry.collection(), origin);
- }
- spdlog::trace("Applied replicated drop collection {} from {}",
- entry.collection(), entry.node_id());
- break;
- }
- default:
- spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
- break;
- }
- } catch (const std::exception& e) {
- spdlog::error("Failed to apply replicated entry: {}", e.what());
- }
- }
- void DatabaseService::startGrpcServer() {
- if (config_.listeners.empty()) {
- // Should never hit — parseConfig's back-compat shim always
- // synthesises at least one. Defend anyway.
- throw std::runtime_error("startGrpcServer: no listeners configured");
- }
- const int64_t mb = 1024 * 1024;
- spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
- config_.grpc.maxReceiveMessageSizeMb,
- config_.grpc.maxSendMessageSizeMb,
- config_.grpc.resourceQuotaMemoryMb,
- config_.grpc.maxConcurrentSubscribeStreams,
- config_.grpc.maxConcurrentFileStreams);
- grpcServers_.reserve(config_.listeners.size());
- for (const auto& listener : config_.listeners) {
- const std::string addr = listener.bind + ":" + std::to_string(listener.port);
- grpc::ServerBuilder builder;
- // v2.4 — choose credentials per listener. Plaintext for
- // tls.enabled=false; SslServerCredentials with the operator's
- // cert+key (or an auto-generated self-signed pair) for true.
- std::shared_ptr<grpc::ServerCredentials> creds;
- if (listener.tls.enabled) {
- std::filesystem::path cert_path = listener.tls.cert_path;
- std::filesystem::path key_path = listener.tls.key_path;
- // Resolve cert+key. If either is missing/unreadable AND
- // auto_self_signed_if_missing is set, generate a pair.
- const bool cert_ok = !cert_path.empty()
- && std::filesystem::exists(cert_path);
- const bool key_ok = !key_path.empty()
- && std::filesystem::exists(key_path);
- if (!cert_ok || !key_ok) {
- if (!listener.tls.auto_self_signed_if_missing) {
- throw std::runtime_error(
- "TLS listener " + addr +
- ": cert or key missing and auto_self_signed_if_missing=false");
- }
- const auto out_dir = config_.dataDirectory / "tls";
- auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
- out_dir, listener.bind);
- cert_path = gen.cert_path;
- key_path = gen.key_path;
- spdlog::warn(
- "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
- "auto-generated self-signed cert at '{}' (key '{}'). "
- "OK for dev. For production, drop a real cert + key at "
- "the configured cert_path/key_path.",
- addr,
- listener.tls.cert_path.string(),
- listener.tls.key_path.string(),
- cert_path.string(),
- key_path.string());
- }
- auto slurp = [](const std::filesystem::path& p) {
- std::ifstream f(p);
- if (!f) throw std::runtime_error("read " + p.string());
- std::stringstream ss; ss << f.rdbuf();
- return ss.str();
- };
- grpc::SslServerCredentialsOptions sslOpts;
- grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
- kp.private_key = slurp(key_path);
- kp.cert_chain = slurp(cert_path);
- sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
- creds = grpc::SslServerCredentials(sslOpts);
- } else {
- creds = grpc::InsecureServerCredentials();
- }
- // v2.4 Stage D — attach the bearer-token auth processor when
- // the listener requires it. The processor validates the
- // `authorization: Bearer <key>` metadata against the listener's
- // configured keys list. gRPC rejects with UNAUTHENTICATED
- // (no per-handler code needed).
- if (listener.auth.required) {
- if (listener.auth.keys.empty()) {
- throw std::runtime_error(
- "Listener " + addr + ": auth.required=true but auth.keys is empty");
- }
- // v2.7.0 — a key name is a principal, so it must be unambiguous.
- // Refuse at startup rather than resolving a policy against a name
- // that means two different callers.
- {
- std::set<std::string> seen;
- for (const auto& k : listener.auth.keys) {
- if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
- smartbotic::database::auth::isReservedPrincipal(k.name)) {
- throw std::runtime_error(
- "Listener " + addr + ": auth key name '" + k.name +
- "' is reserved. `anonymous` denotes an unauthenticated "
- "caller and `unnamed` denotes a legacy bare key; a real "
- "key must not be able to impersonate either in a policy.");
- }
- if (!seen.insert(k.name).second &&
- k.name != smartbotic::database::auth::kPrincipalUnnamed) {
- throw std::runtime_error(
- "Listener " + addr + ": duplicate auth key name '" +
- k.name + "'. A principal must identify one caller, "
- "otherwise a policy written against it is ambiguous.");
- }
- }
- }
- if (!listener.tls.enabled) {
- // gRPC ABORTS the process if an auth metadata processor is
- // attached to insecure credentials
- // (insecure_server_credentials.cc: "assertion failed: 0").
- // This used to be a WARN, which meant a plaintext+auth listener
- // looked merely inadvisable in the config and then killed the
- // server on start with an unexplained assert. Refuse it here
- // with a message that says what to do instead.
- throw std::runtime_error(
- "Listener " + addr + ": auth.required=true requires "
- "tls.enabled=true. gRPC does not support an auth metadata "
- "processor on insecure credentials and will abort the "
- "process. Enable TLS for this listener (set "
- "tls.auto_self_signed_if_missing for a local dev cert), or "
- "drop auth and rely on binding to loopback.");
- }
- std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
- nk.reserve(listener.auth.keys.size());
- for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
- creds->SetAuthMetadataProcessor(
- std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
- std::move(nk)));
- }
- builder.AddListeningPort(addr, creds);
- builder.RegisterService(storageImpl_.get());
- builder.RegisterService(replicationImpl_.get());
- builder.SetMaxReceiveMessageSize(
- static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
- builder.SetMaxSendMessageSize(
- static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
- grpc::ResourceQuota quota("smartbotic-db-" + addr);
- quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
- builder.SetResourceQuota(quota);
- auto server = builder.BuildAndStart();
- if (!server) {
- throw std::runtime_error("Failed to start gRPC server on " + addr);
- }
- // v2.4 Stage B log line — listener identity printed so operators
- // know exactly which interface is exposed with which policy.
- // Stage C/D will extend with TLS + auth status.
- spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
- addr,
- listener.tls.enabled ? "true" : "false",
- listener.auth.required ? "true" : "false");
- grpcServers_.push_back(std::move(server));
- }
- }
- void DatabaseService::stopGrpcServer() {
- // ⚠ Shutdown() WITHOUT a deadline waits for every in-flight RPC to return,
- // and it does NOT cancel them. `Subscribe` never returns on its own: its
- // handler parks in `while (!context->IsCancelled())`, and that context is
- // cancelled only when the client goes away or a shutdown DEADLINE expires.
- // So a single connected subscriber - the normal state of any consumer using
- // events - hung this call forever.
- //
- // The cost is not just a slow stop. `stop()` calls this FIRST and takes the
- // final snapshot AFTER it, so the hang blocked the snapshot; systemd then
- // SIGKILLed at TimeoutStopSec=300, and the next boot recovered by WAL-only
- // replay, which trips auto read-only mode and needs an operator `unlock`.
- // A graceful restart therefore looked like a crash to the next boot.
- //
- // With a deadline, gRPC cancels whatever is still running once it expires,
- // the Subscribe loops observe IsCancelled() and unwind, and shutdown
- // proceeds. The deadline is ABSOLUTE and shared across listeners, so the
- // total wait is bounded by the grace period rather than by
- // grace × listener count.
- //
- // Five seconds: long enough for an ordinary unary RPC in flight to finish
- // (they are milliseconds), short enough that it is invisible next to the
- // final snapshot, which is the part of shutdown that legitimately takes
- // time (~70 s on the largest known dataset).
- // v2.11.2 — tell the parked streaming handlers to return BEFORE asking gRPC
- // to shut down. Subscribe has no work of its own; it waits for the stream to
- // end. Without this signal it learned of the stop only when the deadline
- // below expired and gRPC cancelled it, so every stop paid the full grace
- // period. With it, the streams are usually gone before Shutdown is even
- // called and the deadline is what it should be: a backstop, not the
- // mechanism.
- if (storageImpl_) {
- storageImpl_->beginShutdown();
- }
- constexpr auto kShutdownGrace = std::chrono::seconds(5);
- const auto deadline = std::chrono::system_clock::now() + kShutdownGrace;
- for (auto& server : grpcServers_) {
- if (server) server->Shutdown(deadline);
- }
- grpcServers_.clear();
- }
- } // namespace smartbotic::database
|