database_service.cpp 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730
  1. #include "database_service.hpp"
  2. #include "json_parse.hpp"
  3. #include "project_addressing.hpp"
  4. #include "storage/secondary_index.hpp"
  5. #include "storage/document_store.hpp"
  6. #include "storage/document_store_lmdb.hpp"
  7. #include "storage/dual_write_mirror.hpp"
  8. #include "relations/relation_cascade.hpp"
  9. #include "relations/relation_enforcement.hpp"
  10. #include "auth/auth_interceptor.hpp"
  11. #include "auth/principal.hpp"
  12. #include "tls/cert_generator.hpp"
  13. #include <fstream>
  14. #include <sstream>
  15. #include <map>
  16. #include <set>
  17. #include <algorithm>
  18. #include <chrono>
  19. #include <iterator>
  20. #include "storage/lmdb_env.hpp"
  21. #include "storage/migrate_v1_to_v2.hpp"
  22. #include "storage/project_store.hpp"
  23. #include "storage/subdb_placement.hpp"
  24. #include <grpcpp/grpcpp.h>
  25. #include <grpcpp/resource_quota.h>
  26. #include <spdlog/spdlog.h>
  27. #include <fstream>
  28. #ifdef HAVE_SYSTEMD
  29. #include <systemd/sd-daemon.h>
  30. #endif
  31. #if defined(__GLIBC__) && !defined(__APPLE__)
  32. #include <malloc.h>
  33. #endif
  34. namespace smartbotic::database {
  35. DatabaseService::DatabaseService(Config config)
  36. : config_(std::move(config))
  37. {
  38. }
  39. DatabaseService::~DatabaseService() {
  40. stop();
  41. }
  42. std::string DatabaseService::readOnlyReason() const {
  43. std::lock_guard<std::mutex> lock(reason_mutex_);
  44. return read_only_reason_;
  45. }
  46. void DatabaseService::setReadOnly(bool value, const std::string& reason) {
  47. {
  48. std::lock_guard<std::mutex> lock(reason_mutex_);
  49. read_only_reason_ = value ? reason : "";
  50. }
  51. bool prev = read_only_.exchange(value, std::memory_order_acq_rel);
  52. if (prev != value) {
  53. if (value) {
  54. spdlog::error("Database entered READ-ONLY mode: {}", reason);
  55. } else {
  56. spdlog::info("Database unlocked -- writes accepted");
  57. }
  58. }
  59. }
  60. bool DatabaseService::initialize() {
  61. spdlog::info("Initializing database service (node: {})", config_.nodeId);
  62. try {
  63. // Create data directory if needed
  64. std::error_code ec;
  65. std::filesystem::create_directories(config_.dataDirectory, ec);
  66. if (ec) {
  67. spdlog::error("Failed to create data directory: {}", ec.message());
  68. return false;
  69. }
  70. setupComponents();
  71. // Initialize encryption
  72. if (config_.encryptionEnabled) {
  73. if (!encryption_->initialize()) {
  74. spdlog::error("Failed to initialize encryption");
  75. return false;
  76. }
  77. }
  78. // Recover from persistence
  79. recovery_outcome_ = persistence_->recover(*store_);
  80. #if defined(__GLIBC__) && !defined(__APPLE__)
  81. // v1.9.3 — release freelist pages accumulated during recovery. v1.9.1
  82. // added trim at end of loadSnapshot, but the WAL replay phase that
  83. // runs afterward (`persistence_->recover`'s `replayWal` step) also
  84. // burns through GBs of small Document JSON allocations whose pages
  85. // sit on the per-thread freelist with no subsequent allocation to
  86. // shake them loose. On Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md update 15:05)
  87. // this was 5.7 GB at 23 min uptime — fully reclaimable via
  88. // malloc_trim, just nothing called it. Paired with the periodic
  89. // every-5-minute trim in MemoryStore::logMemoryCheck, so any
  90. // post-boot bloat that escapes this trim gets cleaned up shortly.
  91. ::malloc_trim(0);
  92. #endif
  93. if (recovery_outcome_.isFailure()) {
  94. const std::string modeStr =
  95. recoveryModeToString(config_.persistenceConfig.recoveryMode);
  96. spdlog::error("");
  97. spdlog::error("+------------------------------------------------------------------+");
  98. spdlog::error("| RECOVERY REFUSED |");
  99. spdlog::error("| |");
  100. spdlog::error("| Mode: {}", modeStr);
  101. spdlog::error("| Expected snapshot: {}", recovery_outcome_.expectedSnapshot.string());
  102. spdlog::error("| Reason: {}", recovery_outcome_.failureReason);
  103. spdlog::error("| |");
  104. spdlog::error("| Snapshots available: {}", recovery_outcome_.snapshotsAvailable);
  105. spdlog::error("| Snapshots attempted: {}", recovery_outcome_.snapshotsAttempted);
  106. spdlog::error("| |");
  107. spdlog::error("| To escalate, restart with one of: |");
  108. spdlog::error("| --recovery-mode=snapshot_fallback Try older snapshots |");
  109. spdlog::error("| --recovery-mode=wal_only Replay WAL only (slow) |");
  110. spdlog::error("| --recovery-mode=best_effort Try all of the above |");
  111. spdlog::error("| --recovery-mode=force_empty Start empty (LAST RESORT) |");
  112. spdlog::error("| |");
  113. spdlog::error("| Or set in config.json: \"recovery\": {{ \"mode\": \"<mode>\" }} |");
  114. spdlog::error("| |");
  115. spdlog::error("| PRESERVE /var/lib/smartbotic-database/ BEFORE ESCALATING. |");
  116. spdlog::error("+------------------------------------------------------------------+");
  117. throw std::runtime_error("recovery failed; refusing to start");
  118. }
  119. // Auto-readonly mode on non-trivial recovery
  120. if (recovery_outcome_.isNonTrivial() && !force_readwrite_) {
  121. std::string reason;
  122. switch (recovery_outcome_.kind) {
  123. case RecoveryOutcome::Kind::SnapshotFellBack:
  124. reason = "fell back to snapshot " +
  125. recovery_outcome_.snapshotUsed.filename().string() +
  126. " because " +
  127. recovery_outcome_.expectedSnapshot.filename().string() +
  128. " failed: " + recovery_outcome_.failureReason;
  129. break;
  130. case RecoveryOutcome::Kind::WalOnlyReplay:
  131. reason = "WAL-only replay, no snapshot loaded (" +
  132. std::to_string(recovery_outcome_.walEntriesReplayed) +
  133. " entries)";
  134. break;
  135. case RecoveryOutcome::Kind::ForcedEmpty:
  136. reason = "forced empty by operator (--recovery-mode=force_empty)";
  137. break;
  138. default:
  139. reason = "non-trivial recovery";
  140. break;
  141. }
  142. reason += ". Run `smartbotic-db-cli unlock` to accept this state, "
  143. "or restart with --force-readwrite to bypass this check.";
  144. setReadOnly(true, reason);
  145. spdlog::error("");
  146. spdlog::error("+------------------------------------------------------------------+");
  147. spdlog::error("| [ERROR] Database booted in READ-ONLY mode after non-trivial |");
  148. spdlog::error("| recovery. |");
  149. spdlog::error("| |");
  150. spdlog::error("| Reason: {}", reason);
  151. spdlog::error("| |");
  152. spdlog::error("| Writes will be REJECTED until you acknowledge this state: |");
  153. spdlog::error("| smartbotic-db-cli unlock # live, no restart |");
  154. spdlog::error("| smartbotic-database --force-readwrite # on next restart |");
  155. spdlog::error("+------------------------------------------------------------------+");
  156. }
  157. // Set replication sequence after recovery (WAL sequence is now known)
  158. replication_->setSequence(persistence_->currentWalSequence());
  159. // v1.8.0 — start the persistence manager before loadFromStore /
  160. // migrations so any system-collection writes those phases produce
  161. // (view docs, _collection_meta entries, _migrations recordings)
  162. // reach the WAL like normal mutations. Pre-v1.8, persistence_ was
  163. // started later in start(), which silently dropped those writes
  164. // (running_=false → logInsert no-op). That meant migrated views
  165. // only "survived" because the runner re-created them every boot,
  166. // and a manually-created view that landed during the racy startup
  167. // window (before full readiness) could be lost.
  168. if (!persistence_->start()) {
  169. spdlog::error("Failed to start persistence manager before migrations");
  170. return false;
  171. }
  172. // Load view definitions from the _views system collection (which is now
  173. // populated by the persistence recovery above).
  174. view_manager_->loadFromStore();
  175. // Load per-collection configs from the _collection_meta system collection.
  176. // Must happen AFTER persistence recovery and BEFORE migrations so any
  177. // migration-created documents are stamped with the correct precision.
  178. config_manager_->loadFromStore();
  179. policy_manager_->loadFromStore();
  180. relation_manager_->loadFromStore();
  181. applyRelationDeclarations();
  182. // v2.11.0 close-out — teach the TTL sweeper about relations. Installed
  183. // HERE, after loadFromStore() and the arming pass, deliberately: the
  184. // hook consults the declaration cache and the reverse index, and an
  185. // expiry that fired before either was ready would have decided from an
  186. // empty cache. Until this line the sweeper behaves exactly as it did
  187. // pre-v2.11.0 (which is also what every unit fixture that never
  188. // installs the hook keeps doing).
  189. store_->setTtlExpiryRelationHook(
  190. [this](const std::string& qualifiedCollection, const std::string& id,
  191. bool firstAttempt) {
  192. return ttlExpiryRelationDecision(qualifiedCollection, id, firstAttempt);
  193. });
  194. // v2.9.0 — re-apply persisted index declarations to each project's LMDB
  195. // store. This is load-bearing, not bookkeeping: the declaration is what
  196. // makes the write path maintain an index, and the planner consults an
  197. // index purely on the declaration's word. If this step were skipped, a
  198. // restart would leave indexes recorded but unmaintained, and queries
  199. // would be served from a frozen index - stale rows returned as current,
  200. // with nothing logged.
  201. applyIndexDeclarations();
  202. applySchemaDeclarations(); // v2.16.0
  203. // v2.11.0 final review (finding 4) — THE POST-REPLAY RE-MIRROR PASS
  204. // RUNS HERE, and the position is load-bearing.
  205. //
  206. // PersistenceManager::recover() (above, before any of the arming
  207. // steps) only collects the id list. The pass writes documents through
  208. // LmdbDocumentStore::put(), which reads indexed_fields(),
  209. // unique_fields() and relations() LIVE and maintains every index
  210. // inside the document's own write transaction. Run from inside
  211. // recover(), all three maps were still empty, so it repaired the
  212. // document and left every posting derived from it stale: an
  213. // index-served query then returns the row under its OLD value and
  214. // misses it under its new one - silently wrong rows, which is exactly
  215. // what putting maintainIndexes() inside the transaction exists to
  216. // prevent, and which bit any install with a v2.9 index declared
  217. // whether or not it uses relations. It also made the reverse-index
  218. // half of relation_cascade.hpp's convergence claim false, and made
  219. // UniqueViolation (and therefore the pass's own retry phase)
  220. // unreachable.
  221. //
  222. // Must be after applyRelationDeclarations() AND
  223. // applyIndexDeclarations(); backfillIntoDocStore() below already sits
  224. // at this point for the same reason. Never throws.
  225. #ifdef HAVE_SYSTEMD
  226. // v2.21.4 - after a long replay this pass covers every id it touched.
  227. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  228. sd_notify(0, "STATUS=Re-mirroring replayed documents to LMDB");
  229. #endif
  230. persistence_->runPendingRemirror(*store_, recovery_outcome_);
  231. // Run migrations if enabled
  232. if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
  233. if (!runMigrations()) {
  234. if (config_.migrations.failOnError) {
  235. spdlog::error("Failed to run migrations");
  236. return false;
  237. }
  238. spdlog::warn("Some migrations failed, continuing anyway");
  239. }
  240. }
  241. // v2.0 Stage 4 — synchronous backfill into doc_store_ before
  242. // serving. Without this, only post-boot writes land in LMDB and
  243. // the read-flip downstream would see an empty mirror.
  244. backfillIntoDocStore();
  245. // v2.4.4 — placement audit. Reports documents sitting in a sub-db
  246. // other than the one they declare, which is the signature of a
  247. // misbound MDB_dbi (see storage/subdb_identity.hpp). Read-only and
  248. // advisory: it never blocks startup, because a misplacement is a
  249. // data-location problem an operator repairs offline with
  250. // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
  251. // service on the other 99% of the dataset.
  252. // 2.20.1 - each remaining boot step logs its start, so a boot that
  253. // dies here (a production crash loop on 2026-10-19 died about 3 s
  254. // after the backfill line, with nothing logged) shows which step.
  255. spdlog::info("Boot: sub-db placement audit");
  256. auditSubdbPlacement();
  257. // v2.20.2 - rows LMDB holds that MemoryStore does not (readable, and
  258. // before 2.20.2 not writable), and the reverse. Read-only, advisory.
  259. spdlog::info("Boot: mirror-pending replay");
  260. replayMirrorPending();
  261. spdlog::info("Boot: memory/disk version audit");
  262. repairStaleResidentRows();
  263. spdlog::info("Boot: memory/disk key audit");
  264. auditMemoryDiskKeys();
  265. // v2.6.0 — stamp `project: "default"` onto file records written before
  266. // files were namespaced. Idempotent, and advisory: a file-metadata
  267. // stamp is not a reason to refuse service, so failures warn only.
  268. if (files_) {
  269. spdlog::info("Boot: file records");
  270. try {
  271. const uint32_t stamped = files_->stampMissingProjects();
  272. if (stamped > 0) {
  273. spdlog::info("v2.6.0 file migration: stamped {} legacy file "
  274. "record(s) with project 'default'", stamped);
  275. } else {
  276. spdlog::debug("v2.6.0 file migration: no legacy file records");
  277. }
  278. } catch (const std::exception& e) {
  279. spdlog::warn("v2.6.0 file migration failed: {}", e.what());
  280. }
  281. }
  282. // v2.11.0 close-out — LAST ACT OF THE BOOT PATH, and the position is
  283. // load-bearing. Everything above that can bump the drift counter (the
  284. // post-replay re-mirror pass, backfillIntoDocStore(), a malformed
  285. // legacy collection key) is now behind the baseline, so
  286. // mirrorDriftSinceReady() reports only drift a LIVE write caused.
  287. // Destructive relation policies gate on that, not on the raw counter:
  288. // see MemoryStore::markMirrorDriftBaseline() for the trap this closes
  289. // (one unrepairable row disabling every cascade/set_null delete and
  290. // every CreateRelation for the process's life, with an error message
  291. // telling the operator to restart, which re-incurs it). Reads keep
  292. // gating on the RAW counter - a stale row genuinely means MemoryStore
  293. // is ahead, and that fallback must stay.
  294. // v2.17.0 - encrypt what must be encrypted, and remove the plaintext
  295. // copies, before anything can read or replicate them.
  296. spdlog::info("Boot: encryption at rest");
  297. migrateEncryptionAtRest();
  298. store_->markMirrorDriftBaseline();
  299. if (store_->mirrorDriftBaseline() > 0) {
  300. spdlog::warn("mirror drift at READY: {} - accrued on the boot path (see the "
  301. "ERROR lines above for the exact rows). Reads for this process "
  302. "will be served from MemoryStore rather than LMDB. Destructive "
  303. "relation policies are NOT disabled by this, but the rows named "
  304. "above are still stale in LMDB until each is rewritten through "
  305. "an ordinary write; a restart re-attempts and, if the cause "
  306. "persists, re-incurs the same count.",
  307. store_->mirrorDriftBaseline());
  308. }
  309. spdlog::info("Database service initialized successfully");
  310. return true;
  311. } catch (const std::exception& e) {
  312. spdlog::error("Failed to initialize database service: {}", e.what());
  313. return false;
  314. }
  315. }
  316. void DatabaseService::migrateLegacyEnvToDefaultProject() {
  317. const auto legacy = config_.dataDirectory / "env";
  318. const auto target = config_.dataDirectory / "projects" /
  319. smartbotic::database::kDefaultProject / "env";
  320. std::error_code ec;
  321. const bool legacy_exists = std::filesystem::exists(legacy, ec);
  322. const bool target_exists = std::filesystem::exists(target, ec);
  323. if (!legacy_exists) return; // fresh install or already migrated
  324. if (target_exists) {
  325. spdlog::error("v2.3 storage: both legacy '{}' and new '{}' exist — "
  326. "refusing to start. Inspect manually; the safe move is "
  327. "to either delete the legacy dir (if you confirm it's a "
  328. "leftover) or stop and contact ops.",
  329. legacy.string(), target.string());
  330. throw std::runtime_error("v2.3 storage migration: ambiguous layout");
  331. }
  332. std::filesystem::create_directories(target.parent_path(), ec);
  333. if (ec) {
  334. throw std::runtime_error("v2.3 storage migration: cannot create '"
  335. + target.parent_path().string() + "': " + ec.message());
  336. }
  337. std::filesystem::rename(legacy, target, ec);
  338. if (ec) {
  339. throw std::runtime_error("v2.3 storage migration: rename '"
  340. + legacy.string() + "' -> '"
  341. + target.string() + "' failed: " + ec.message());
  342. }
  343. spdlog::info("v2.3 storage: migrated legacy env '{}' -> '{}' (default project)",
  344. legacy.string(), target.string());
  345. }
  346. smartbotic::db::storage::DocumentStore* DatabaseService::docStore() noexcept {
  347. return docStore(smartbotic::database::kDefaultProject);
  348. }
  349. smartbotic::db::storage::DocumentStore*
  350. DatabaseService::docStore(std::string_view project) noexcept {
  351. if (!projects_) return nullptr;
  352. return projects_->get(project);
  353. }
  354. std::vector<std::string> DatabaseService::listProjects() const {
  355. if (!projects_) return {};
  356. return projects_->listOnDisk();
  357. }
  358. bool DatabaseService::createProject(const std::string& name, std::string& error) {
  359. if (!projects_) {
  360. error = "project registry not initialized";
  361. return false;
  362. }
  363. return projects_->create(name, error);
  364. }
  365. bool DatabaseService::dropProject(const std::string& name, std::string& error) {
  366. if (!projects_) {
  367. error = "project registry not initialized";
  368. return false;
  369. }
  370. // v2.11.0 close-out — capture the relation declarations belonging to this
  371. // project BEFORE the drop. Relations are validated same-project at
  372. // creation (no LMDB transaction spans two envs), so `child` and `parent`
  373. // are always in the same project as `name` itself; listRelations(name)
  374. // therefore names every declaration the drop invalidates. Captured first
  375. // because listRelations needs the project to still be nameable and, more
  376. // importantly, because un-arming needs the store to still exist.
  377. std::vector<RelationInfo> doomed;
  378. if (relation_manager_) {
  379. try {
  380. doomed = relation_manager_->listRelations(name);
  381. } catch (const std::exception& e) {
  382. spdlog::warn("v2.11 relations: could not enumerate relations of project '{}' "
  383. "before dropping it ({}); its declarations may be left behind",
  384. name, e.what());
  385. }
  386. }
  387. if (!projects_->drop(name, error)) return false;
  388. // v2.12.2 - collection configs live in the GLOBAL `_collection_meta`, not
  389. // in the project's env, so dropping the env left every one of the project's
  390. // declarations behind - and a recreated project silently inherited them.
  391. // The index sub-dbs went with the env; only the records remain to remove.
  392. if (config_manager_) {
  393. const std::string prefix = name + ":";
  394. size_t removed = 0;
  395. for (const auto& [key, cfg] : config_manager_->allConfigs()) {
  396. if (key.rfind(prefix, 0) == 0 && config_manager_->removeConfig(key)) ++removed;
  397. }
  398. if (removed > 0) {
  399. spdlog::info("dropProject '{}': removed {} collection config(s)", name, removed);
  400. }
  401. }
  402. // ---- The drop succeeded; the declarations now point at a namespace that
  403. // no longer exists. Sweep them out of the global `_relations` collection
  404. // and un-arm each affected child collection.
  405. //
  406. // Order (drop first, sweep second) is deliberate: the registry is the one
  407. // that refuses "default" and rejects unknown names, so sweeping first would
  408. // destroy declarations for a project whose drop then failed. The cost of
  409. // this order is that the per-project store is usually already gone by the
  410. // time we try to un-arm, which makes the un-arm a no-op - correct, since a
  411. // store that no longer exists cannot be maintaining a reverse index. It
  412. // still runs, because ProjectStoreRegistry may hold a live
  413. // LmdbDocumentStore for a re-created project of the same name.
  414. //
  415. // ⚠ Advisory, never fatal: the project IS dropped at this point, and a
  416. // leftover declaration is litter, not corruption (its child and parent
  417. // collections are both gone, so nothing can be enforced against them). A
  418. // failure here must not report the drop as failed.
  419. for (const auto& r : doomed) {
  420. try {
  421. std::string err;
  422. if (!relation_manager_->dropRelation(r.name, err)) {
  423. spdlog::warn("v2.11 relations: could not drop declaration '{}' left by "
  424. "dropped project '{}': {}", r.name, name, err);
  425. continue;
  426. }
  427. const auto rc = resolveCollection(r.child);
  428. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
  429. docStore(rc.project));
  430. if (lmdb != nullptr) {
  431. // Empty list = "this collection has no relations", which is what
  432. // set_relations replaces the previous list with. Every relation
  433. // of a dropped project goes, so clearing the child wholesale is
  434. // exactly right here (unlike DropRelation, which must re-arm the
  435. // survivors).
  436. lmdb->set_relations(rc.collection, {});
  437. }
  438. spdlog::info("v2.11 relations: dropped declaration '{}' with the project '{}'",
  439. r.name, name);
  440. } catch (const std::exception& e) {
  441. spdlog::warn("v2.11 relations: could not clean up declaration '{}' after "
  442. "dropping project '{}': {}", r.name, name, e.what());
  443. }
  444. }
  445. // ⚠ KNOWN, NOT FIXED HERE (v2.11.0 close-out): _views, _policies and
  446. // _collection_meta have the SAME gap - ProjectStoreRegistry::drop() removes
  447. // the project's env and nothing else, so a dropped project leaves its view
  448. // definitions, access policies and per-collection configs behind in those
  449. // global system collections too. Not a shared fix: each manager keys and
  450. // caches differently (ViewManager keys `<project>:<name>`, PolicyManager
  451. // `<project>:<principal>`, CollectionConfigManager `<project>:<collection>`
  452. // and canonicalises the cache key only), so each needs its own sweep, and
  453. // PolicyManager's has a security dimension this one does not (a re-created
  454. // project inheriting a stale policy). Scoped out deliberately; recorded so
  455. // it is not rediscovered as new.
  456. return true;
  457. }
  458. bool DatabaseService::runMigrations() {
  459. if (!config_.migrations.enabled) {
  460. return true;
  461. }
  462. MigrationRunner::Config migrationConfig;
  463. migrationConfig.directory = config_.migrations.directory;
  464. migrationConfig.autoApply = config_.migrations.autoApply;
  465. migrationConfig.failOnError = config_.migrations.failOnError;
  466. migrationRunner_ = std::make_unique<MigrationRunner>(
  467. *store_, *view_manager_, *relation_manager_, migrationConfig);
  468. migrationRunner_->setDocumentPreparer([this](const std::string& collection, Document& doc) {
  469. encryption_->encryptSensitiveFields(doc, encryptionRuleFor(collection)); // v2.17.0
  470. });
  471. const bool ok = migrationRunner_->runMigrations();
  472. // v2.11.0 close-out — a `create_relation` migration op only PERSISTS the
  473. // declaration. Arming the write path and building the reverse index over
  474. // rows that already exist is what applyRelationDeclarations() does, and it
  475. // has already run for this boot (initialize() calls it before migrations),
  476. // so without this a migration-declared relation would maintain no reverse
  477. // index and enforce nothing until the NEXT restart - the "declared but not
  478. // enforcing" state this feature's self-heal exists to make unreachable.
  479. // Idempotent and cheap: re-arming an already-armed child replaces an
  480. // identical list, and the bootstrap loop skips any relation whose index
  481. // sub-db already exists. Runs even when the migration run reported failure,
  482. // because a partially-applied run may still have created a relation.
  483. applyRelationDeclarations(/*afterMigrations=*/true);
  484. return ok;
  485. }
  486. nlohmann::json DatabaseService::schemaView(const nlohmann::json& body) const {
  487. nlohmann::json copy = body;
  488. if (copy.is_object()) {
  489. stripReservedFields(copy);
  490. copy.erase("_vector");
  491. }
  492. encryption_->decryptTree(copy);
  493. return copy;
  494. }
  495. DatabaseService::AtRestStats DatabaseService::encryptCollectionAtRest(const std::string& collection) {
  496. AtRestStats st;
  497. if (!encryption_ || !encryption_->isEnabled()) return st;
  498. const EncryptionRule rule = encryptionRuleFor(collection);
  499. const auto transform = [&](nlohmann::json& body) { return encryption_->encryptTree(body, rule); };
  500. // LMDB holds every row (MemoryStore may have evicted some); find the rows
  501. // that still hold plaintext, then rewrite each under the collection lock.
  502. smartbotic::db::storage::DocumentStore* ds = nullptr;
  503. std::string bare;
  504. // The names MemoryStore may hold this collection's rows under: the
  505. // qualified form and, in the default project, the bare one (see
  506. // MemoryStore::encryptionOptionsFor). Both map to the same LMDB sub-db.
  507. std::vector<std::string> names{collection};
  508. try {
  509. const auto rc = smartbotic::database::resolveCollection(collection);
  510. ds = docStore(rc.project);
  511. bare = rc.collection;
  512. if (rc.qualified != collection) names.push_back(rc.qualified);
  513. if (rc.project == smartbotic::database::kDefaultProject && rc.collection != collection) {
  514. names.push_back(rc.collection);
  515. }
  516. } catch (const std::exception&) {
  517. }
  518. std::vector<std::string> ids;
  519. if (ds != nullptr) {
  520. ds->export_scan(bare, "", false, nullptr, [](uint64_t) {},
  521. [&](Document&& d, smartbotic::db::storage::DocumentStore::ExportVectorState,
  522. const float*, size_t) -> bool {
  523. ++st.scanned;
  524. EncryptionManager::TreeAudit a;
  525. encryption_->auditTree(d.data(), rule, a);
  526. if (a.plaintextRequired > 0) ids.push_back(d.id);
  527. return true;
  528. });
  529. }
  530. for (const auto& id : ids) {
  531. int r = -1;
  532. for (const auto& n : names) {
  533. r = store_->rewriteBodyInPlace(n, id, transform);
  534. if (r != -1) break;
  535. }
  536. if (r == 1) {
  537. ++st.rewritten;
  538. } else if (r == -1 && ds != nullptr) {
  539. // Not in MemoryStore at all: the LMDB row is the only copy.
  540. if (auto d = ds->get(bare, id)) {
  541. nlohmann::json b = d->data();
  542. if (transform(b)) {
  543. d->set_data(b);
  544. d->encrypted = true;
  545. ds->put(bare, id, *d);
  546. ++st.lmdbOnly;
  547. }
  548. }
  549. }
  550. }
  551. if (history_store_) {
  552. for (const auto& n : names) {
  553. st.versions += history_store_->rewrite(n, [&](DocumentVersion& v) {
  554. nlohmann::json b = v.data();
  555. if (!transform(b)) return false;
  556. v.set_data(b);
  557. v.encrypted = true;
  558. return true;
  559. });
  560. }
  561. }
  562. return st;
  563. }
  564. void DatabaseService::requestResealAtNextBoot(const std::string& project) {
  565. std::ofstream(config_.dataDirectory / "encryption-reseal.pending", std::ios::app)
  566. << (project.empty() ? "*" : project) << "\n";
  567. }
  568. void DatabaseService::migrateEncryptionAtRest() {
  569. namespace fs = std::filesystem;
  570. const fs::path marker = config_.dataDirectory / "encryption-at-rest.v1";
  571. const fs::path reseal = config_.dataDirectory / "encryption-reseal.pending";
  572. std::error_code ec;
  573. const bool firstRun = !fs::exists(marker, ec);
  574. const bool resealPending = fs::exists(reseal, ec);
  575. if (!encryption_ || !encryption_->isEnabled()) {
  576. if (firstRun) spdlog::warn("v2.17 at-rest: encryption is disabled; nothing is encrypted at rest");
  577. return;
  578. }
  579. if (!firstRun && !resealPending) return;
  580. AtRestStats total;
  581. if (firstRun) {
  582. spdlog::warn("v2.17 at-rest: one-time migration - encrypting values stored in plaintext "
  583. "that must be encrypted (encrypted collections, sensitive_fields, the "
  584. "sensitive name patterns at any depth)");
  585. std::set<std::string> done; // canonical names: aliases share one LMDB sub-db
  586. for (const auto& coll : store_->listCollections()) {
  587. if (coll.empty() || coll[0] == '_') continue;
  588. std::string canonical = coll;
  589. try {
  590. canonical = smartbotic::database::resolveCollection(coll).qualified;
  591. } catch (const std::exception&) {
  592. }
  593. if (!done.insert(canonical).second) continue;
  594. #ifdef HAVE_SYSTEMD
  595. // Each collection is a scan plus a history rewrite: on a large
  596. // dataset the whole pass outlasts TimeoutStartSec. Same protocol
  597. // the v1 migration and recovery use.
  598. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  599. sd_notify(0, ("STATUS=Encrypting at rest: " + canonical).c_str());
  600. #endif
  601. const auto s = encryptCollectionAtRest(canonical);
  602. total.scanned += s.scanned;
  603. total.rewritten += s.rewritten;
  604. total.lmdbOnly += s.lmdbOnly;
  605. total.versions += s.versions;
  606. if (s.rewritten + s.lmdbOnly + s.versions > 0) {
  607. spdlog::warn("v2.17 at-rest: {}: {} row(s) and {} history version(s) encrypted "
  608. "(of {} row(s) scanned)", canonical, s.rewritten + s.lmdbOnly, s.versions,
  609. s.scanned);
  610. }
  611. }
  612. spdlog::warn("v2.17 at-rest: {} row(s) scanned, {} encrypted in place ({} LMDB-only), "
  613. "{} history version(s) encrypted", total.scanned,
  614. total.rewritten + total.lmdbOnly, total.lmdbOnly, total.versions);
  615. }
  616. // The seal: the rewrite replaced plaintext in the live stores, but older
  617. // snapshots, the WAL and LMDB's freed pages still hold it.
  618. std::string err;
  619. size_t snaps = 0, wals = 0;
  620. if (!persistence_->sealAfterRewrite(*store_, err, snaps, wals)) {
  621. spdlog::error("v2.17 at-rest: seal FAILED ({}); old plaintext copies remain in the WAL / "
  622. "snapshots. Serving continues; the next boot retries.", err);
  623. requestResealAtNextBoot();
  624. return;
  625. }
  626. // v2.17.2 - which envs to compact. The first run compacts every project.
  627. // A reseal compacts only the projects named in the pending file; "*" (a
  628. // failure path) or a pre-2.17.2 file (its content was "1") means all.
  629. // 2.17.1 compacted every project on any reseal: a 262 MB env the upgrade
  630. // never touched cost 2.5 minutes of a restart and reclaimed nothing.
  631. bool compactAll = firstRun;
  632. std::set<std::string> toCompact;
  633. if (!firstRun) {
  634. std::ifstream in(reseal);
  635. std::string line;
  636. while (std::getline(in, line)) {
  637. if (line.empty()) continue;
  638. if (line == "*" || line == "1") compactAll = true;
  639. else toCompact.insert(line);
  640. }
  641. if (toCompact.empty()) compactAll = true;
  642. }
  643. size_t compacted = 0;
  644. for (const auto& p : projects_->listOpen()) {
  645. if (!compactAll && !toCompact.count(p)) continue;
  646. ++compacted;
  647. uint64_t before = 0, after = 0;
  648. std::string cerr;
  649. if (projects_->compact(p, before, after, cerr)) {
  650. spdlog::info("v2.17 at-rest: project '{}' compacted, {} -> {} bytes", p, before, after);
  651. } else {
  652. spdlog::error("v2.17 at-rest: project '{}' compaction failed: {} - freed pages may "
  653. "still hold old plaintext; the next boot retries", p, cerr);
  654. requestResealAtNextBoot(p);
  655. applyIndexDeclarations();
  656. applyRelationDeclarations(/*afterMigrations=*/true);
  657. return;
  658. }
  659. }
  660. // Compaction reopened every env: per-store arming must be applied again.
  661. applyIndexDeclarations();
  662. applyRelationDeclarations(/*afterMigrations=*/true);
  663. std::ofstream(marker) << "encrypted at rest by 2.17.0\n";
  664. fs::remove(reseal, ec);
  665. spdlog::warn("v2.17 at-rest: sealed - {} old snapshot(s) and {} WAL file(s) removed, {} "
  666. "project(s) compacted{}. Copies made BEFORE this boot (backups, pre-upgrade copies, "
  667. "replicas, disk blocks) are outside the database's reach.", snaps, wals, compacted,
  668. compactAll ? " (all)" : "");
  669. }
  670. void DatabaseService::applySchemaDeclarations() {
  671. size_t armed = 0;
  672. for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
  673. if (!cfg.schema) continue;
  674. auto compiled = smartbotic::db::schema::compile(*cfg.schema);
  675. if (!compiled.schema) {
  676. // Loud: the record says this collection is constrained and it is
  677. // not. Only a hand-edited record can get here (the RPC refuses
  678. // anything that does not compile).
  679. spdlog::error("v2.16 schema: the schema stored for {} does not compile ({}); "
  680. "it is NOT enforced until it is set again", qualified, compiled.error);
  681. continue;
  682. }
  683. auto entry = std::make_shared<smartbotic::db::schema::SchemaEntry>();
  684. entry->compiled = compiled.schema;
  685. entry->source = *cfg.schema;
  686. entry->audit = cfg.schemaMode == "audit";
  687. schemas_.set(qualified, entry);
  688. ++armed;
  689. spdlog::info("v2.16 schema: {} armed ({})", qualified, entry->audit ? "audit" : "enforce");
  690. }
  691. if (armed > 0) spdlog::info("v2.16 schema: {} collection schema(s) armed", armed);
  692. }
  693. void DatabaseService::applyIndexDeclarations() {
  694. size_t applied = 0;
  695. for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
  696. if (cfg.indexedFields.empty() && cfg.compositeUniques.empty()) continue;
  697. try {
  698. const auto rc = resolveCollection(qualified);
  699. auto* ds = docStore(rc.project);
  700. auto* lmdb =
  701. dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  702. if (lmdb == nullptr) continue;
  703. // v2.17.0 - an index over a field stored encrypted indexes
  704. // ciphertext under random IVs: lookups never hit and a unique
  705. // constraint never fires. Such declarations are disarmed (neither
  706. // maintained nor consulted) and named, so the operator drops them.
  707. CollectionCfg armed = cfg;
  708. if (encryption_ && encryption_->isEnabled()) {
  709. const EncryptionRule rule = encryptionRuleFor(qualified);
  710. const auto enc = [&](const std::string& f) {
  711. return !isReservedField(f) && encryption_->isEncryptedPath(f, rule);
  712. };
  713. const auto strip = [&](std::vector<std::string>& v, const char* what) {
  714. for (auto it = v.begin(); it != v.end();) {
  715. if (enc(*it)) {
  716. spdlog::error("v2.17 encryption: {} on {}#{} is DISARMED - the field is "
  717. "stored encrypted. Drop it.", what, qualified, *it);
  718. it = v.erase(it);
  719. } else {
  720. ++it;
  721. }
  722. }
  723. };
  724. strip(armed.indexedFields, "index");
  725. strip(armed.uniqueFields, "unique constraint");
  726. for (auto it = armed.compositeUniques.begin(); it != armed.compositeUniques.end();) {
  727. if (std::any_of(it->begin(), it->end(), enc)) {
  728. spdlog::error("v2.17 encryption: a composite unique constraint on {} is "
  729. "DISARMED - one of its fields is stored encrypted. Drop it.",
  730. qualified);
  731. it = armed.compositeUniques.erase(it);
  732. } else {
  733. ++it;
  734. }
  735. }
  736. }
  737. lmdb->set_indexed_fields(rc.collection, armed.indexedFields);
  738. // v2.11.0 T11 — arm uniqueFields the same way. This is the fix
  739. // for the exact failure mode the type was built to avoid:
  740. // uniqueFields has been persisted since T8 with no RPC or proto
  741. // surface, which was safe (nothing consulted it); now that
  742. // set_unique_fields is reachable, a restart that skipped this
  743. // call would silently stop enforcing a constraint every write
  744. // handler still advertises as active.
  745. lmdb->set_unique_fields(rc.collection, armed.uniqueFields);
  746. // v2.12.0 - composite constraints, armed the same way and for the
  747. // same reason: skipping this would stop enforcing a constraint the
  748. // record still declares. Self-healed below if its sub-db is gone.
  749. lmdb->set_composite_uniques(rc.collection, armed.compositeUniques);
  750. for (const auto& cf : armed.compositeUniques) {
  751. if (lmdb->has_composite_unique_subdb(rc.collection, cf)) continue;
  752. uint64_t rows = 0;
  753. auto dupes = lmdb->build_composite_unique(rc.collection, cf, rows);
  754. if (dupes.empty()) {
  755. spdlog::warn("v2.12 composite unique: rebuilt {}#({}) over {} row(s) - "
  756. "declared but its sub-db was absent",
  757. qualified, smartbotic::db::storage::composite_display_name(cf), rows);
  758. } else {
  759. // Cannot happen through the API (declaring over duplicates is
  760. // refused). If it does, say so loudly: the constraint stays
  761. // declared and armed, but rows already violating it exist.
  762. spdlog::error("v2.12 composite unique: {}#({}) is declared but {} "
  763. "existing value combination(s) violate it (e.g. document "
  764. "'{}'); its index could not be rebuilt. Writes that would "
  765. "add another duplicate are still refused.",
  766. qualified, smartbotic::db::storage::composite_display_name(cf),
  767. dupes.size(), dupes.front().sample_id);
  768. }
  769. }
  770. ++applied;
  771. spdlog::info("v2.9 index: {} field(s) active on {} ({} unique)",
  772. cfg.indexedFields.size(), qualified, cfg.uniqueFields.size());
  773. // Self-heal a declared index whose sub-db is absent. That happens
  774. // when the KEY FORMAT VERSION in the sub-db prefix changes (v2.9.1
  775. // unified the numeric encoding, so `_idx_` became `_idx2_`), and it
  776. // would otherwise leave the declaration pointing at nothing: writes
  777. // would maintain the new index correctly, but rows written BEFORE the
  778. // upgrade would have no postings, so an indexed query would silently
  779. // return only the newer ones. Rebuilding is the only safe reading.
  780. for (const auto& field : armed.indexedFields) {
  781. if (lmdb->index_stats(rc.collection, field).has_value()) continue;
  782. const uint64_t rows = lmdb->build_index(rc.collection, field);
  783. spdlog::warn("v2.9 index: rebuilt {}#{} over {} row(s) - the index "
  784. "was declared but its sub-db was absent (key format "
  785. "change or a manual removal)",
  786. qualified, field, rows);
  787. }
  788. } catch (const std::exception& e) {
  789. // Advisory per collection: one unparseable name must not stop the
  790. // rest from being armed. Loud, because a missing declaration means
  791. // that collection's index silently stops being maintained.
  792. spdlog::error("v2.9 index: could not apply declarations for {}: {}",
  793. qualified, e.what());
  794. }
  795. }
  796. if (applied > 0) {
  797. spdlog::info("v2.9 index: applied declarations for {} collection(s)", applied);
  798. }
  799. }
  800. MemoryStore::TtlExpiryAction DatabaseService::ttlExpiryRelationDecision(
  801. const std::string& qualifiedCollection, const std::string& id, bool firstAttempt) {
  802. using Action = MemoryStore::TtlExpiryAction;
  803. // Thin binder over relations/relation_cascade.cpp's ttlExpiryDecision() -
  804. // the policy itself lives there so it is unit-testable against the same
  805. // fixtures the cascade tests use, without a DatabaseService. All this does
  806. // is resolve the per-project LMDB store and supply the replication/events
  807. // notifier.
  808. if (!relation_manager_ || !config_manager_ || !store_ || !persistence_) {
  809. return Action::Proceed;
  810. }
  811. if (qualifiedCollection.empty() || qualifiedCollection[0] == '_') return Action::Proceed;
  812. try {
  813. const auto rc = resolveCollection(qualifiedCollection);
  814. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
  815. docStore(rc.project));
  816. // No LMDB substrate means no reverse index to consult, so the
  817. // pre-v2.11.0 behaviour is all that is available.
  818. if (lmdb == nullptr) return Action::Proceed;
  819. // Replication + Subscribe events, driven per mutation - the same wiring
  820. // DatabaseGrpcImpl::performRelationCascade() uses. Without it a
  821. // TTL-driven cascade would be invisible to followers and subscribers,
  822. // and a follower that never saw the child deletions diverges
  823. // permanently (the v2.3.1 class of bug).
  824. // v2.12.0 - an expiry has no caller, so every event this cascade
  825. // produces carries an explicitly EMPTY actor. Letting it default
  826. // would report a nulled child's previous writer as the cause.
  827. auto notify = [this](const std::string& coll, const std::string& docId,
  828. const std::optional<Document>& doc, EventType eventType) {
  829. notifyReplicationAndEvents(coll, docId, doc, eventType, std::string{});
  830. };
  831. // firstAttempt -> the refusal (if any) is logged at WARN; a retry of an
  832. // already-reported document logs at DEBUG. The sweeper owns that
  833. // decision because it is the only thing that knows the document has
  834. // been refused before.
  835. return smartbotic::database::ttlExpiryDecision(
  836. *relation_manager_, *lmdb, *persistence_, *store_, *config_manager_,
  837. qualifiedCollection, id, notify, firstAttempt);
  838. } catch (const std::exception& e) {
  839. // Never expire a parent whose children could not be evaluated.
  840. spdlog::error("TTL expiry of '{}/{}': could not resolve its storage ({}) - the "
  841. "document is left in place and will be retried",
  842. qualifiedCollection, id, e.what());
  843. return Action::Skip;
  844. }
  845. }
  846. void DatabaseService::applyRelationDeclarations(bool afterMigrations) {
  847. // Group by (project, bare child collection) — set_relations() is a
  848. // per-collection call on that project's LmdbDocumentStore and replaces
  849. // whatever was declared before, so every relation sharing a child
  850. // collection must land in one call.
  851. std::unordered_map<std::string,
  852. std::vector<smartbotic::db::storage::RelationRef>> byChild;
  853. // Track which project each grouping key belongs to alongside the bare
  854. // collection name, since the map key alone doesn't carry it.
  855. std::unordered_map<std::string, std::pair<std::string, std::string>> keyToProjectCollection;
  856. for (const auto& r : relation_manager_->listRelations()) {
  857. try {
  858. const auto rn = resolveCollection(r.name);
  859. const auto rc = resolveCollection(r.child);
  860. // v2.11.0 T13 — parent resolved to its bare name, same reasoning
  861. // as armRelationsForChild's mirror of this construction.
  862. const auto pc = resolveCollection(r.parent);
  863. const std::string key = rc.project + ":" + rc.collection;
  864. // v2.11.0 T13 round 2 — snapshot relationsEnforced at boot-time
  865. // arming, same reasoning as armRelationsForChild's mirror of
  866. // this construction. `key` is already the qualified child name
  867. // configFor expects.
  868. const bool enforced = config_manager_->configFor(key).relationsEnforced;
  869. byChild[key].push_back(smartbotic::db::storage::RelationRef{
  870. rn.collection, r.childField, pc.collection, r.validateOnWrite, enforced});
  871. keyToProjectCollection[key] = {rc.project, rc.collection};
  872. } catch (const std::exception& e) {
  873. // Advisory per relation: one unparseable declaration must not
  874. // stop the rest from being armed. Loud, because a skipped
  875. // relation silently maintains no reverse index for its child.
  876. spdlog::error("v2.11 relations: could not apply declaration '{}': {}",
  877. r.name, e.what());
  878. }
  879. }
  880. size_t applied = 0;
  881. for (const auto& [key, refs] : byChild) {
  882. const auto& [project, collection] = keyToProjectCollection[key];
  883. try {
  884. // ⚠ v2.11.0 close-out — getOrCreate, not get(), on the POST-MIGRATION
  885. // pass. docStore() is projects_->get(), which does NOT create an env,
  886. // and a `create_relation` migration in a project that has never been
  887. // written to has no env yet: the declaration persisted, this pass
  888. // skipped it, and the relation maintained no reverse index and
  889. // enforced NOTHING until the next restart - the exact
  890. // "declared but not enforcing" state the op was added to avoid, just
  891. // narrowed to new projects. A migration declaring a relation IS a
  892. // statement that the project exists, and the mirror resolver would
  893. // getOrCreate the same env on the first write anyway.
  894. //
  895. // The BOOT pass deliberately keeps get(): creating envs there would
  896. // resurrect the env of a project whose declarations are merely stale.
  897. auto* ds = (afterMigrations && projects_)
  898. ? projects_->getOrCreate(project)
  899. : docStore(project);
  900. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  901. if (lmdb == nullptr) continue;
  902. lmdb->set_relations(collection, refs);
  903. ++applied;
  904. spdlog::info("v2.11 relations: {} relation(s) active with child '{}:{}'",
  905. refs.size(), project, collection);
  906. // v2.11.0 T7 self-heal — mirrors applyIndexDeclarations()'s
  907. // rebuild of a declared-but-absent index sub-db, for the same
  908. // reason: a relation whose reverse index sub-db is missing is
  909. // exactly the "declared but not enforcing" bug this task exists
  910. // to close. Reachable paths that leave a relation in this state:
  911. // a snapshot/backup restored from before the sub-db existed, or
  912. // an operator manually dropping the `_relidx1_*` sub-db (there
  913. // is no dropRelation-only-the-index tool). CreateRelation's own
  914. // bootstrap scan (see database_grpc_impl.cpp) covers the normal
  915. // declare-time path; this covers everything else.
  916. //
  917. // ⚠ v2.11.0 close-out (review minor 2) — the SAME code path is the
  918. // NORMAL, expected one for a relation a migration just declared:
  919. // migrations run after this pass, so runMigrations() calls it again
  920. // and the brand-new relation legitimately has no sub-db yet. Logging
  921. // "declared but its sub-db was absent (restored snapshot or a manual
  922. // removal)" at WARN there describes a fault that did not happen.
  923. // `afterMigrations` distinguishes the two so the text and the level
  924. // match the event.
  925. for (const auto& ref : refs) {
  926. if (lmdb->relation_index_exists(ref.name)) continue;
  927. const uint64_t rows =
  928. lmdb->build_relation_index(ref.name, collection, ref.childField);
  929. if (afterMigrations) {
  930. spdlog::info("v2.11 relations: built the reverse index for '{}' over {} "
  931. "existing row(s) in '{}:{}' - a migration declared this "
  932. "relation on this boot",
  933. ref.name, rows, project, collection);
  934. } else {
  935. spdlog::warn("v2.11 relations: rebuilt '{}' over {} row(s) in '{}:{}' - the "
  936. "relation was declared but its reverse index sub-db was absent "
  937. "(restored snapshot predating it, or a manual removal)",
  938. ref.name, rows, project, collection);
  939. }
  940. }
  941. } catch (const std::exception& e) {
  942. spdlog::error("v2.11 relations: could not apply declarations for '{}:{}': {}",
  943. project, collection, e.what());
  944. }
  945. }
  946. if (applied > 0) {
  947. spdlog::info("v2.11 relations: applied declarations for {} child collection(s)", applied);
  948. }
  949. }
  950. void DatabaseService::auditSubdbPlacement() {
  951. if (!projects_) return;
  952. for (const auto& name : projects_->listOpen()) {
  953. auto h = projects_->getHandle(name);
  954. if (!h.env) continue;
  955. try {
  956. // audit_env(), NOT audit(). The path-taking overload opens a
  957. // second MDB_env on the same file; closing it would drop the
  958. // POSIX record locks this process already holds for `h.env`
  959. // (POSIX locks are per-process, and closing any fd on a file
  960. // releases all of them), leaving every later mdb_txn_begin
  961. // failing EINVAL. Borrow the open handle instead.
  962. const auto rep = smartbotic::db::storage::audit_env(h.env->raw(), name);
  963. if (rep.misplaced.empty()) {
  964. spdlog::debug("placement audit: project '{}' consistent ({} rows)",
  965. name, rep.rows_scanned);
  966. continue;
  967. }
  968. // Summarise per (physical -> declared home) pair; one line per
  969. // affected document would be unreadable at scale.
  970. std::map<std::string, uint64_t> pairs;
  971. for (const auto& m : rep.misplaced) {
  972. ++pairs[m.physical_subdb + " -> " + m.home_subdb];
  973. }
  974. spdlog::error("placement audit: project '{}' has {} document(s) in the "
  975. "wrong sub-db. Reads served from LMDB will not find them "
  976. "under their own collection. Repair offline with: "
  977. "smartbotic-db-cli reconcile-subdbs --env {} --project {} --apply",
  978. name, rep.misplaced.size(), h.env->path(), name);
  979. for (const auto& [pair, count] : pairs) {
  980. spdlog::error("placement audit: {} document(s) {}", count, pair);
  981. }
  982. } catch (const std::exception& e) {
  983. // Advisory only — a failed audit must not take the service down.
  984. spdlog::warn("placement audit: project '{}' could not be audited: {}",
  985. name, e.what());
  986. }
  987. }
  988. }
  989. void DatabaseService::recordMirrorFailure(const std::string& collection, const std::string& id) {
  990. if (!mirror_pending_) return;
  991. if (!mirror_pending_->append(collection, id)) {
  992. spdlog::error("mirror-pending: could not record {}/{} in {} - if a snapshot truncates "
  993. "its WAL entry before the next boot, only the boot key audit will find it",
  994. collection, id, mirror_pending_->path().string());
  995. }
  996. }
  997. void DatabaseService::replayMirrorPending() {
  998. if (!mirror_pending_ || !store_) return;
  999. const auto rows = mirror_pending_->load();
  1000. if (rows.empty()) return;
  1001. spdlog::warn("mirror-pending: {} row(s) whose LMDB copy failed earlier; bringing LMDB in "
  1002. "line with memory", rows.size());
  1003. const auto r = store_->syncDocStoreFromMemory(rows);
  1004. if (!mirror_pending_->replace(r.failed)) {
  1005. spdlog::error("mirror-pending: could not rewrite {}", mirror_pending_->path().string());
  1006. }
  1007. if (r.failed.empty()) {
  1008. spdlog::info("mirror-pending: repaired {} row(s): {} written, {} deleted from LMDB",
  1009. rows.size(), r.written, r.deleted);
  1010. } else {
  1011. spdlog::error("mirror-pending: {} written, {} deleted, {} still failing (kept for the "
  1012. "next boot; reads for this process are served from memory)",
  1013. r.written, r.deleted, r.failed.size());
  1014. }
  1015. }
  1016. // v2.21.4 - a production boot replayed 193,776 of the 354,089 WAL entries
  1017. // above its snapshot (cause under investigation; the per-file replay lines
  1018. // now show where entries go). LMDB had every write, because each one was
  1019. // mirrored at write time, so reads were right; MemoryStore kept the snapshot's
  1020. // older version of every row written in the gap, and MemoryStore is the base
  1021. // of a patch (old fields + the patch, mirrored over LMDB's newer row), of
  1022. // updateIfVersion's check, of history and of the next snapshot - which then
  1023. // made the old version permanent. The key audit compares ids only, so it saw
  1024. // nothing.
  1025. //
  1026. // LMDB is authoritative here: the re-mirror pass and the mirror-pending replay
  1027. // have already written to LMDB every row for which memory is authoritative
  1028. // (rows the replay applied, rows whose LMDB copy failed), so a difference that
  1029. // remains means memory is behind. Runs before the listener starts (no writer
  1030. // races it) and only while the mirror is healthy with zero drift. Reads every
  1031. // resident row of every mirrored collection from LMDB once.
  1032. uint64_t DatabaseService::repairStaleResidentRows() {
  1033. if (!projects_ || !store_) return 0;
  1034. if (!mirror_healthy_.load(std::memory_order_relaxed) ||
  1035. mirror_drift_count_.load(std::memory_order_relaxed) != 0) {
  1036. spdlog::warn("version audit: skipped (the LMDB mirror is unhealthy or has drift, so "
  1037. "LMDB may be behind memory)");
  1038. return 0;
  1039. }
  1040. namespace sd = smartbotic::database;
  1041. const auto started = std::chrono::steady_clock::now();
  1042. uint64_t checked = 0, reloaded = 0, failed = 0, memNewerTotal = 0;
  1043. constexpr size_t kBatch = 256;
  1044. for (const auto& name : store_->listCollections()) {
  1045. sd::ResolvedCollection rc;
  1046. try {
  1047. rc = sd::resolveCollection(name);
  1048. } catch (const std::exception&) {
  1049. continue;
  1050. }
  1051. if (rc.collection.empty() || rc.collection.front() == '_') continue;
  1052. auto* ds = docStore(rc.project);
  1053. if (!ds) continue;
  1054. const auto ids = store_->getDocumentIds(name);
  1055. std::vector<std::string> stale; // LMDB newer: reloaded
  1056. std::vector<std::string> memNewer; // memory newer: reported, left alone
  1057. std::string detail, memDetail; // both sides of the first few, for the log
  1058. for (size_t from = 0; from < ids.size(); from += kBatch) {
  1059. const auto mem = store_->copyDocuments(name, ids, from, kBatch);
  1060. for (size_t k = 0; k < mem.size(); ++k) {
  1061. if (!mem[k]) continue; // deleted meanwhile
  1062. ++checked;
  1063. std::optional<Document> disk;
  1064. try {
  1065. disk = ds->get(rc.collection, ids[from + k]);
  1066. } catch (const std::exception& e) {
  1067. ++failed;
  1068. spdlog::warn("version audit: {}/{}: LMDB read failed: {}",
  1069. name, ids[from + k], e.what());
  1070. continue;
  1071. }
  1072. if (!disk) continue; // memory only: the key audit reports it
  1073. if (disk->version == mem[k]->version && disk->updatedAt == mem[k]->updatedAt) {
  1074. continue;
  1075. }
  1076. // Which side is newer: the later _updated_at (ms and ns
  1077. // stamps coexist; 10^15 tells them apart), then the higher
  1078. // version. Only an LMDB-newer row is reloaded.
  1079. const auto ns = [](uint64_t t) { return t < 1'000'000'000'000'000ULL ? t * 1'000'000ULL : t; };
  1080. const uint64_t dt = ns(disk->updatedAt), mt = ns(mem[k]->updatedAt);
  1081. const bool diskNewer = dt != mt ? dt > mt : disk->version > mem[k]->version;
  1082. auto& list = diskNewer ? stale : memNewer;
  1083. auto& text = diskNewer ? detail : memDetail;
  1084. if (list.size() < 5) {
  1085. text += fmt::format("{}{} (memory v{} at {}, LMDB v{} at {})",
  1086. list.empty() ? "" : "; ", ids[from + k],
  1087. mem[k]->version, mem[k]->updatedAt,
  1088. disk->version, disk->updatedAt);
  1089. }
  1090. list.push_back(ids[from + k]);
  1091. }
  1092. }
  1093. if (!memNewer.empty()) {
  1094. // An old LMDB copy that missed a write (a mirror failure before
  1095. // 2.21.0 recorded them): memory holds the later write. Left as it
  1096. // is; reads have been showing LMDB's older copy, and the next
  1097. // write to the row mirrors memory's version over it.
  1098. memNewerTotal += memNewer.size();
  1099. spdlog::warn("version audit: {}: {} resident row(s) are NEWER than LMDB's copy, "
  1100. "left in memory (e.g. {})", name, memNewer.size(), memDetail);
  1101. }
  1102. if (stale.empty()) continue;
  1103. uint64_t done = 0;
  1104. for (const auto& id : stale) {
  1105. try {
  1106. // A reload, not a write: no history entry, no WAL, no event.
  1107. MemoryStore::HistorySuppression noHistory(*store_);
  1108. if (store_->unloadDocument(name, id) && store_->adoptFromDocStore(name, id, true)) {
  1109. ++done;
  1110. } else {
  1111. ++failed;
  1112. }
  1113. } catch (const std::exception& e) {
  1114. ++failed;
  1115. spdlog::warn("version audit: {}/{}: reload failed: {}", name, id, e.what());
  1116. }
  1117. }
  1118. reloaded += done;
  1119. spdlog::warn("version audit: {}: {} resident row(s) were older than LMDB's copy, "
  1120. "{} reloaded from LMDB (e.g. {})", name, stale.size(), done, detail);
  1121. }
  1122. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  1123. std::chrono::steady_clock::now() - started).count();
  1124. if (reloaded > 0 || failed > 0 || memNewerTotal > 0) {
  1125. spdlog::warn("version audit: {} resident row(s) checked, {} reloaded from LMDB, "
  1126. "{} newer in memory (left), {} failed ({} ms)",
  1127. checked, reloaded, memNewerTotal, failed, ms);
  1128. } else {
  1129. spdlog::info("version audit: {} resident row(s) agree with LMDB ({} ms)", checked, ms);
  1130. }
  1131. return reloaded;
  1132. }
  1133. void DatabaseService::auditMemoryDiskKeys() {
  1134. if (!projects_ || !store_) return;
  1135. namespace sd = smartbotic::database;
  1136. const auto started = std::chrono::steady_clock::now();
  1137. const std::string& diskPolicy = config_.consistencyDiskOnly;
  1138. const std::string& memPolicy = config_.consistencyMemoryOnly;
  1139. // LMDB sub-db ("project:collection") -> the MemoryStore names that feed
  1140. // it. A default-project collection may also live under its bare legacy
  1141. // name; both resolve to one sub-db, so both count as "in memory".
  1142. std::map<std::string, std::vector<std::string>> memNames;
  1143. for (const auto& name : store_->listCollections()) {
  1144. try {
  1145. auto rc = sd::resolveCollection(name);
  1146. if (rc.collection.empty() || rc.collection.front() == '_') continue;
  1147. memNames[rc.qualified].push_back(name);
  1148. } catch (const std::exception&) {
  1149. continue; // a malformed legacy key; the backfill already reported it
  1150. }
  1151. }
  1152. const auto samples = [](const std::vector<std::string>& ids) {
  1153. std::string out;
  1154. for (size_t i = 0; i < ids.size() && i < 10; ++i) {
  1155. if (i) out += ", ";
  1156. out += ids[i];
  1157. }
  1158. if (ids.size() > 10) out += ", ... (all in consistency-report.json)";
  1159. return out;
  1160. };
  1161. nlohmann::json report = {
  1162. {"policy", {{"disk_only", diskPolicy}, {"memory_only", memPolicy}}},
  1163. {"collections", nlohmann::json::array()},
  1164. };
  1165. uint64_t diskOnlyTotal = 0, memOnlyTotal = 0, compared = 0;
  1166. uint64_t adopted = 0, diskRemoved = 0, written = 0, memRemoved = 0, actionFailed = 0;
  1167. uint64_t notAdoptable = 0; // disk-only rows whose collection exists only on disk
  1168. for (const auto& project : projects_->listOpen()) {
  1169. auto* ds = docStore(project);
  1170. if (!ds) continue;
  1171. std::set<std::string> collections;
  1172. try {
  1173. for (auto& c : ds->list_collections()) collections.insert(std::move(c));
  1174. } catch (const std::exception& e) {
  1175. spdlog::warn("key audit: project '{}' could not be listed: {}", project, e.what());
  1176. continue;
  1177. }
  1178. const std::string prefix = project + sd::kProjectSeparator;
  1179. for (const auto& [qualified, names] : memNames) {
  1180. if (qualified.rfind(prefix, 0) == 0) collections.insert(qualified.substr(prefix.size()));
  1181. }
  1182. for (const auto& coll : collections) {
  1183. if (coll.empty() || coll.front() == '_') continue;
  1184. const std::string qualified = prefix + coll;
  1185. try {
  1186. auto disk = ds->list_ids(coll);
  1187. if (!disk) continue; // backend cannot list
  1188. // id -> the MemoryStore name holding it (the first alias wins).
  1189. std::vector<std::pair<std::string, std::string>> mem;
  1190. const auto namesIt = memNames.find(qualified);
  1191. if (namesIt != memNames.end()) {
  1192. for (const auto& n : namesIt->second) {
  1193. for (auto& id : store_->getDocumentIds(n)) mem.emplace_back(std::move(id), n);
  1194. for (auto& id : store_->getEvictedDocumentIds(n)) mem.emplace_back(std::move(id), n);
  1195. }
  1196. }
  1197. std::stable_sort(mem.begin(), mem.end(),
  1198. [](const auto& a, const auto& b) { return a.first < b.first; });
  1199. mem.erase(std::unique(mem.begin(), mem.end(),
  1200. [](const auto& a, const auto& b) { return a.first == b.first; }),
  1201. mem.end());
  1202. std::sort(disk->begin(), disk->end()); // already key order; cheap insurance
  1203. std::vector<std::string> diskOnly;
  1204. std::vector<std::pair<std::string, std::string>> memOnly; // id, memory name
  1205. {
  1206. size_t i = 0, j = 0;
  1207. while (i < disk->size() || j < mem.size()) {
  1208. if (j == mem.size() || (i < disk->size() && (*disk)[i] < mem[j].first)) {
  1209. diskOnly.push_back((*disk)[i++]);
  1210. } else if (i == disk->size() || mem[j].first < (*disk)[i]) {
  1211. memOnly.push_back(mem[j++]);
  1212. } else {
  1213. ++i; ++j;
  1214. }
  1215. }
  1216. }
  1217. ++compared;
  1218. if (diskOnly.empty() && memOnly.empty()) continue;
  1219. nlohmann::json entry = {{"collection", qualified}};
  1220. if (!diskOnly.empty()) {
  1221. diskOnlyTotal += diskOnly.size();
  1222. // Adoption needs the collection in memory (its options:
  1223. // vector dimension, TTL); one only on disk is reported.
  1224. const bool inMemory = namesIt != memNames.end();
  1225. std::vector<std::string> done, failed;
  1226. if (diskPolicy == "adopt" && inMemory) {
  1227. const std::string target = std::find(namesIt->second.begin(),
  1228. namesIt->second.end(), qualified)
  1229. != namesIt->second.end()
  1230. ? qualified : namesIt->second.front();
  1231. for (const auto& id : diskOnly) {
  1232. try {
  1233. (store_->adoptFromDocStore(target, id, /*quiet=*/true) ? done : failed).push_back(id);
  1234. } catch (const std::exception& e) {
  1235. spdlog::error("key audit: adopting {}/{} failed: {}", qualified, id, e.what());
  1236. failed.push_back(id);
  1237. }
  1238. }
  1239. adopted += done.size();
  1240. } else if (diskPolicy == "remove") {
  1241. for (const auto& id : diskOnly) {
  1242. try {
  1243. ds->del(coll, id);
  1244. ds->del_vector(coll, id);
  1245. done.push_back(id);
  1246. } catch (const std::exception& e) {
  1247. spdlog::error("key audit: removing {}/{} from disk failed: {}",
  1248. qualified, id, e.what());
  1249. failed.push_back(id);
  1250. }
  1251. }
  1252. diskRemoved += done.size();
  1253. }
  1254. actionFailed += failed.size();
  1255. // Counted under every policy, so `report` can price `adopt`
  1256. // before anything acts (asked by smartbotic-vectorapi).
  1257. if (!inMemory) notAdoptable += diskOnly.size();
  1258. const std::string action =
  1259. diskPolicy == "report"
  1260. ? (inMemory ? "reported (adopt would load them)"
  1261. : "reported (not adoptable: the collection exists only on disk)") :
  1262. (diskPolicy == "adopt" && !inMemory)
  1263. ? "reported (not adoptable: the collection exists only on disk)" :
  1264. diskPolicy == "adopt" ? "adopted into memory (loaded unchanged)" : "removed from disk";
  1265. spdlog::warn("key audit: {}: {} row(s) on disk but not in memory (reads find them; "
  1266. "2.20.2+ loads one when it is written) - {}{}{}. ids: {}",
  1267. qualified, diskOnly.size(), action,
  1268. diskPolicy == "report" ? "; set storage.consistency.disk_only to adopt "
  1269. "(load into memory) or remove (delete from disk)"
  1270. : "",
  1271. failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
  1272. samples(diskOnly));
  1273. entry["disk_only"] = {{"action", action}, {"collection_in_memory", inMemory},
  1274. {"ids", diskOnly}, {"failed", failed}};
  1275. }
  1276. if (!memOnly.empty()) {
  1277. memOnlyTotal += memOnly.size();
  1278. std::vector<std::string> ids, failed;
  1279. for (const auto& [id, n] : memOnly) ids.push_back(id);
  1280. if (memPolicy == "write") {
  1281. std::vector<std::pair<std::string, std::string>> rows;
  1282. for (const auto& [id, n] : memOnly) rows.emplace_back(n, id);
  1283. const auto r = store_->syncDocStoreFromMemory(rows);
  1284. written += r.written;
  1285. for (const auto& [c, id] : r.failed) failed.push_back(id);
  1286. } else if (memPolicy == "remove") {
  1287. for (const auto& [id, n] : memOnly) {
  1288. try {
  1289. if (store_->remove(n, id, "system:consistency-repair")) ++memRemoved;
  1290. else failed.push_back(id);
  1291. } catch (const std::exception& e) {
  1292. spdlog::error("key audit: removing {}/{} from memory failed: {}",
  1293. qualified, id, e.what());
  1294. failed.push_back(id);
  1295. }
  1296. }
  1297. }
  1298. actionFailed += failed.size();
  1299. const std::string action =
  1300. memPolicy == "report" ? "reported" :
  1301. memPolicy == "write" ? "written to disk" : "removed from memory";
  1302. spdlog::warn("key audit: {}: {} row(s) in memory but not on disk (writes find them, "
  1303. "reads served from disk do not) - {}{}{}. ids: {}",
  1304. qualified, memOnly.size(), action,
  1305. memPolicy == "report" ? "; set storage.consistency.memory_only to write "
  1306. "(make them readable) or remove (delete them)"
  1307. : "",
  1308. failed.empty() ? "" : fmt::format("; {} FAILED", failed.size()),
  1309. samples(ids));
  1310. entry["memory_only"] = {{"action", action}, {"ids", ids}, {"failed", failed}};
  1311. }
  1312. report["collections"].push_back(std::move(entry));
  1313. } catch (const std::exception& e) {
  1314. spdlog::warn("key audit: {} could not be audited: {}", qualified, e.what());
  1315. }
  1316. }
  1317. }
  1318. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  1319. std::chrono::steady_clock::now() - started).count();
  1320. report["compared"] = compared;
  1321. report["disk_only"] = diskOnlyTotal;
  1322. report["memory_only"] = memOnlyTotal;
  1323. report["adopted"] = adopted;
  1324. report["not_adoptable"] = notAdoptable;
  1325. report["milliseconds"] = ms;
  1326. try {
  1327. const auto path = std::filesystem::path(config_.dataDirectory) / "consistency-report.json";
  1328. const auto tmp = path.string() + ".tmp";
  1329. {
  1330. std::ofstream out(tmp, std::ios::trunc);
  1331. out << report.dump(2) << "\n";
  1332. }
  1333. std::filesystem::rename(tmp, path);
  1334. } catch (const std::exception& e) {
  1335. spdlog::warn("key audit: could not write consistency-report.json: {}", e.what());
  1336. }
  1337. if (diskOnlyTotal == 0 && memOnlyTotal == 0) {
  1338. spdlog::info("key audit: {} collection(s) consistent ({} ms)", compared, ms);
  1339. } else {
  1340. spdlog::log(actionFailed > 0 ? spdlog::level::err : spdlog::level::warn,
  1341. "key audit: {} collection(s) compared, {} row(s) on disk only, {} in "
  1342. "memory only ({} ms). Policy disk_only={} memory_only={}: {} adopted, {} "
  1343. "not adoptable (their collection exists only on disk; counted under any "
  1344. "policy), {} removed from "
  1345. "disk, {} written to disk, {} removed from memory, {} failed. "
  1346. "Full lists: consistency-report.json in the data directory.",
  1347. compared, diskOnlyTotal, memOnlyTotal, ms, diskPolicy, memPolicy,
  1348. adopted, notAdoptable, diskRemoved, written, memRemoved, actionFailed);
  1349. }
  1350. }
  1351. bool DatabaseService::backfillIntoDocStore() {
  1352. if (!projects_) {
  1353. // Registry open failed earlier; nothing to back-fill into.
  1354. return true;
  1355. }
  1356. // v2.3 — MemoryStore stores collection keys in qualified form
  1357. // ("project:collection"). For the default project (back-compat
  1358. // path) the marker check operates on the default env. Skip when
  1359. // already migrated.
  1360. auto handle = projects_->getHandle(smartbotic::database::kDefaultProject);
  1361. if (handle.env) {
  1362. try {
  1363. if (smartbotic::db::storage::migration_complete(*handle.env)) {
  1364. spdlog::info("v2.3 backfill: default project already migrated, skipping");
  1365. return true;
  1366. }
  1367. } catch (const std::exception& e) {
  1368. spdlog::warn("v2.3 backfill: migration_complete probe failed: {} — "
  1369. "treating default env as fresh and proceeding",
  1370. e.what());
  1371. }
  1372. }
  1373. const auto collections = store_->listCollections();
  1374. uint64_t total_docs = 0;
  1375. uint64_t total_failures = 0;
  1376. auto t0 = std::chrono::steady_clock::now();
  1377. for (const auto& qualified : collections) {
  1378. if (qualified.empty() || qualified[0] == '_') continue;
  1379. // Each qualified key parses to (project, collection); route the
  1380. // mirror write to the right project's env.
  1381. smartbotic::database::ProjectCollection pc;
  1382. try {
  1383. pc = smartbotic::database::parseProjectCollection(qualified);
  1384. } catch (const std::exception&) {
  1385. // Legacy unqualified key — treat as default project.
  1386. pc = {std::string(smartbotic::database::kDefaultProject), qualified};
  1387. }
  1388. auto* ds = projects_->getOrCreate(pc.project);
  1389. if (!ds) {
  1390. ++total_failures;
  1391. continue;
  1392. }
  1393. const auto docs = store_->getAllDocuments(qualified);
  1394. for (const auto& doc : docs) {
  1395. std::optional<Document> opt_doc(doc);
  1396. const uint64_t drift_before = mirror_drift_count_.load(std::memory_order_relaxed);
  1397. // v2.11.0 T13 round 2 — UniqueViolation/MissingParentReference are
  1398. // rethrown UNCAUGHT by applyDualWriteMirror (deliberately - see
  1399. // both exceptions' header comments), unlike a genuine mirror
  1400. // fault which is swallowed and only shows up as a drift bump
  1401. // below. Uncaught here would escape this loop, backfillIntoDocStore
  1402. // and initialize() itself, refusing startup over one rejected row.
  1403. // Practically unreachable today - backfill only runs migrating a
  1404. // v1.x dataset, which predates both `_relations` and unique-index
  1405. // declarations - but catching removes that reasoning burden for
  1406. // the next reader, same as any other row here that fails.
  1407. try {
  1408. smartbotic::db::storage::applyDualWriteMirror(
  1409. ds, mirror_healthy_, mirror_drift_count_,
  1410. pc.collection, doc.id, opt_doc, EventType::INSERT);
  1411. } catch (const std::exception& e) {
  1412. spdlog::error("v2.3 backfill: mirror rejected {}/{}: {} - row stays "
  1413. "in MemoryStore only, LMDB does not have it",
  1414. qualified, doc.id, e.what());
  1415. ++total_failures;
  1416. }
  1417. if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
  1418. ++total_failures;
  1419. recordMirrorFailure(qualified, doc.id); // v2.21.0
  1420. }
  1421. ++total_docs;
  1422. if (total_docs % 10000 == 0) {
  1423. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  1424. const std::string status = "STATUS=v2.3 backfill: " +
  1425. std::to_string(total_docs) + " docs mirrored";
  1426. sd_notify(0, status.c_str());
  1427. spdlog::info("v2.3 backfill: {} docs mirrored ({} failures so far)",
  1428. total_docs, total_failures);
  1429. }
  1430. }
  1431. }
  1432. const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  1433. std::chrono::steady_clock::now() - t0).count();
  1434. if (total_failures == 0) {
  1435. // Stamp schema_version=2 on every opened project env. Subsequent
  1436. // boots short-circuit at migration_complete().
  1437. for (const auto& name : projects_->listOpen()) {
  1438. auto h = projects_->getHandle(name);
  1439. if (!h.env) continue;
  1440. try {
  1441. smartbotic::db::storage::mark_migration_complete(*h.env);
  1442. } catch (const std::exception& e) {
  1443. spdlog::warn("v2.3 backfill: schema_version marker write failed for "
  1444. "project '{}': {}", name, e.what());
  1445. }
  1446. }
  1447. spdlog::info("v2.3 backfill: complete — {} docs across {} collections in {} ms",
  1448. total_docs, collections.size(), elapsed);
  1449. } else {
  1450. spdlog::error("v2.3 backfill: completed with {} failures out of {} docs "
  1451. "in {} ms — mirror_healthy_=false, reads must NOT flip to LMDB",
  1452. total_failures, total_docs, elapsed);
  1453. }
  1454. return true;
  1455. }
  1456. void DatabaseService::start() {
  1457. if (running_.exchange(true)) {
  1458. return;
  1459. }
  1460. spdlog::info("Starting database service with {} listener(s)", config_.listeners.size());
  1461. // Start components
  1462. store_->start();
  1463. persistence_->start();
  1464. events_->start();
  1465. files_->start();
  1466. if (config_.replicationEnabled) {
  1467. replication_->start();
  1468. // Set initial local collections for discovery
  1469. replication_->setLocalCollections(store_->listCollections());
  1470. }
  1471. // Start gRPC server
  1472. startGrpcServer();
  1473. spdlog::info("Database service started");
  1474. }
  1475. void DatabaseService::stop() {
  1476. if (!running_.exchange(false)) {
  1477. return;
  1478. }
  1479. spdlog::info("Stopping database service...");
  1480. // Stop gRPC server first
  1481. stopGrpcServer();
  1482. // Stop components in reverse order
  1483. if (replication_) {
  1484. replication_->stop();
  1485. }
  1486. if (files_) {
  1487. files_->stop();
  1488. }
  1489. if (events_) {
  1490. events_->stop();
  1491. }
  1492. if (persistence_ && store_) {
  1493. // v1.8.0 — take a final snapshot on graceful shutdown so the next
  1494. // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
  1495. // replay" which trips auto-readonly mode. This makes ordinary
  1496. // restarts pass through cleanly without needing
  1497. // `smartbotic-db-cli unlock`.
  1498. //
  1499. // v1.8.2 — extend systemd's stop watchdog before doing it. On Zoe
  1500. // (1.85M docs / ~5 GB tracked) the serialize takes ~70 s and the
  1501. // default TimeoutStopSec=30s SIGKILLed the process mid-write, peak
  1502. // RSS hit 11 GB (live state + uncompressed serialize buffer), and
  1503. // the new snapshot never made it to disk anyway. EXTEND_TIMEOUT_USEC
  1504. // tells systemd we're working — same protocol the recovery path
  1505. // uses during startup. Paired with TimeoutStopSec=300 in the unit
  1506. // file as the static cap.
  1507. #ifdef HAVE_SYSTEMD
  1508. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  1509. sd_notify(0, "STATUS=Writing final snapshot");
  1510. #endif
  1511. try {
  1512. persistence_->forceSnapshot(*store_);
  1513. spdlog::info("Final snapshot taken on shutdown");
  1514. } catch (const std::exception& e) {
  1515. spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
  1516. "boot may be WAL-only and trip auto-readonly mode", e.what());
  1517. }
  1518. }
  1519. if (persistence_) {
  1520. persistence_->stop();
  1521. }
  1522. if (store_) {
  1523. store_->stop();
  1524. }
  1525. spdlog::info("Database service stopped");
  1526. }
  1527. void DatabaseService::wait() {
  1528. if (serverThread_.joinable()) {
  1529. serverThread_.join();
  1530. }
  1531. }
  1532. void DatabaseService::signalStop() {
  1533. stopRequested_ = true;
  1534. stop();
  1535. }
  1536. nlohmann::json DatabaseService::getStats() const {
  1537. nlohmann::json stats;
  1538. if (store_) {
  1539. auto storeStats = store_->getStats();
  1540. stats["documents"] = storeStats.totalDocuments;
  1541. stats["collections"] = storeStats.totalCollections;
  1542. stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
  1543. stats["inserts"] = storeStats.insertCount;
  1544. stats["updates"] = storeStats.updateCount;
  1545. stats["deletes"] = storeStats.deleteCount;
  1546. stats["queries"] = storeStats.queryCount;
  1547. }
  1548. if (persistence_) {
  1549. auto persistStats = persistence_->getStats();
  1550. stats["wal_sequence"] = persistStats.walSequence;
  1551. stats["wal_size_bytes"] = persistStats.walSizeBytes;
  1552. stats["snapshot_count"] = persistStats.snapshotCount;
  1553. stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
  1554. }
  1555. if (events_) {
  1556. stats["subscriptions"] = events_->subscriptionCount();
  1557. }
  1558. return stats;
  1559. }
  1560. DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
  1561. std::ifstream file(configPath);
  1562. if (!file) {
  1563. throw std::runtime_error("Failed to open config file: " + configPath.string());
  1564. }
  1565. nlohmann::json json;
  1566. file >> json;
  1567. return parseConfig(json);
  1568. }
  1569. DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
  1570. Config config;
  1571. // Check for both "storage" and "database" keys for backward compatibility
  1572. const nlohmann::json* dbConfig = nullptr;
  1573. if (json.contains("database")) {
  1574. dbConfig = &json["database"];
  1575. } else if (json.contains("storage")) {
  1576. dbConfig = &json["storage"];
  1577. }
  1578. if (dbConfig) {
  1579. const auto& db = *dbConfig;
  1580. config.nodeId = db.value("node_id", config.nodeId);
  1581. config.bindAddress = db.value("bind_address", config.bindAddress);
  1582. config.rpcPort = db.value("rpc_port", config.rpcPort);
  1583. if (db.contains("consistency") && db["consistency"].is_object()) {
  1584. const auto& c = db["consistency"];
  1585. config.consistencyDiskOnly = c.value("disk_only", config.consistencyDiskOnly);
  1586. config.consistencyMemoryOnly = c.value("memory_only", config.consistencyMemoryOnly);
  1587. }
  1588. if (config.consistencyDiskOnly != "adopt" && config.consistencyDiskOnly != "report" &&
  1589. config.consistencyDiskOnly != "remove") {
  1590. spdlog::error("storage.consistency.disk_only '{}' is not adopt|report|remove; using report",
  1591. config.consistencyDiskOnly);
  1592. config.consistencyDiskOnly = "report";
  1593. }
  1594. if (config.consistencyMemoryOnly != "report" && config.consistencyMemoryOnly != "write" &&
  1595. config.consistencyMemoryOnly != "remove") {
  1596. spdlog::error("storage.consistency.memory_only '{}' is not report|write|remove; using report",
  1597. config.consistencyMemoryOnly);
  1598. config.consistencyMemoryOnly = "report";
  1599. }
  1600. // v2.4 — parse the per-listener fleet. If "listeners" is set,
  1601. // it overrides the legacy bind_address+rpc_port. Otherwise we
  1602. // synthesise one listener below using those legacy fields.
  1603. if (db.contains("listeners") && db["listeners"].is_array()) {
  1604. for (const auto& l : db["listeners"]) {
  1605. ListenerConfig lc;
  1606. lc.bind = l.value("bind", lc.bind);
  1607. lc.port = l.value("port", lc.port);
  1608. if (l.contains("tls") && l["tls"].is_object()) {
  1609. const auto& t = l["tls"];
  1610. lc.tls.enabled = t.value("enabled", false);
  1611. lc.tls.cert_path = t.value("cert_path", std::string{});
  1612. lc.tls.key_path = t.value("key_path", std::string{});
  1613. lc.tls.auto_self_signed_if_missing =
  1614. t.value("auto_self_signed_if_missing", true);
  1615. }
  1616. if (l.contains("auth") && l["auth"].is_object()) {
  1617. const auto& a = l["auth"];
  1618. lc.auth.required = a.value("required", false);
  1619. if (a.contains("keys") && a["keys"].is_array()) {
  1620. for (const auto& k : a["keys"]) {
  1621. // v2.7.0 — a key is either a bare token (v2.4-v2.6
  1622. // shape) or {"name","key"}. The name becomes the
  1623. // principal that policy is written against; a bare
  1624. // token maps to the reserved `unnamed`, so old
  1625. // configs keep authenticating but cannot be told
  1626. // apart in a policy until they are named.
  1627. if (k.is_string()) {
  1628. lc.auth.keys.push_back(
  1629. {smartbotic::database::auth::kPrincipalUnnamed,
  1630. k.get<std::string>()});
  1631. } else if (k.is_object()) {
  1632. const std::string name = k.value("name", std::string{});
  1633. const std::string key = k.value("key", std::string{});
  1634. if (key.empty()) {
  1635. spdlog::warn("auth: listener {}:{} has a key entry "
  1636. "with no `key` value - skipped",
  1637. lc.bind, lc.port);
  1638. continue;
  1639. }
  1640. lc.auth.keys.push_back(
  1641. {name.empty()
  1642. ? std::string(smartbotic::database::auth::kPrincipalUnnamed)
  1643. : name,
  1644. key});
  1645. }
  1646. }
  1647. }
  1648. }
  1649. config.listeners.push_back(std::move(lc));
  1650. }
  1651. }
  1652. // Expand environment variables in data directory
  1653. std::string dataDir = db.value("data_directory", "");
  1654. if (dataDir.find("${HOME}") != std::string::npos) {
  1655. const char* home = std::getenv("HOME");
  1656. if (home) {
  1657. size_t pos = dataDir.find("${HOME}");
  1658. dataDir.replace(pos, 7, home);
  1659. }
  1660. }
  1661. config.dataDirectory = dataDir;
  1662. // Migrations settings
  1663. if (db.contains("migrations")) {
  1664. auto& migrations = db["migrations"];
  1665. config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
  1666. config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
  1667. config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
  1668. std::string migDir = migrations.value("directory", "");
  1669. if (migDir.find("${HOME}") != std::string::npos) {
  1670. const char* home = std::getenv("HOME");
  1671. if (home) {
  1672. size_t pos = migDir.find("${HOME}");
  1673. migDir.replace(pos, 7, home);
  1674. }
  1675. }
  1676. config.migrations.directory = migDir;
  1677. }
  1678. // Memory eviction settings
  1679. if (db.contains("memory")) {
  1680. auto& memory = db["memory"];
  1681. // No deprecation warning (removed after 2.21.2). From v2.0 these
  1682. // keys logged "deprecated and will be removed in v2.1" at every
  1683. // boot. They were never removed and no removal is planned: they set
  1684. // MemoryStore's budget, eviction and pressure levels, and emergency
  1685. // pressure refuses writes, so they are live controls (and since
  1686. // 2.21.2 the budget covers vectors too). The warning read as stale
  1687. // output from a 2.0 build and invited an operator to delete the
  1688. // budget. MemoryStore goes, and these keys with it, only when the
  1689. // write-handler migration lands (docs/ROADMAP.md, "Pending").
  1690. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  1691. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  1692. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  1693. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  1694. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  1695. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  1696. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  1697. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  1698. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  1699. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  1700. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  1701. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  1702. // v1.7.0 T10 — eviction burst event threshold
  1703. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  1704. // v2.4.3 — eviction drain cap (0 disables)
  1705. config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
  1706. }
  1707. // v2.11.0 close-out — TTL sweep budgets. Its own block rather than
  1708. // `memory`, because these bound expiry work per sweep, not memory.
  1709. if (db.contains("ttl")) {
  1710. auto& ttl = db["ttl"];
  1711. config.ttlMaxCandidatesPerSweep =
  1712. ttl.value("max_candidates_per_sweep", config.ttlMaxCandidatesPerSweep);
  1713. config.ttlMaxBlockedRetriesPerSweep =
  1714. ttl.value("max_blocked_retries_per_sweep", config.ttlMaxBlockedRetriesPerSweep);
  1715. config.ttlBlockedRetrySweeps =
  1716. ttl.value("blocked_retry_sweeps", config.ttlBlockedRetrySweeps);
  1717. config.ttlBlockedSummarySweeps =
  1718. ttl.value("blocked_summary_sweeps", config.ttlBlockedSummarySweeps);
  1719. }
  1720. // Persistence settings
  1721. if (db.contains("persistence")) {
  1722. auto& persistence = db["persistence"];
  1723. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  1724. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  1725. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  1726. // Snapshot durability (NEW in v1.6.1)
  1727. if (persistence.contains("snapshots")) {
  1728. const auto& snap = persistence["snapshots"];
  1729. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  1730. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  1731. }
  1732. // Recovery (NEW in v1.6.1)
  1733. if (persistence.contains("recovery")) {
  1734. const auto& rec = persistence["recovery"];
  1735. std::string modeStr = rec.value("mode", std::string("normal"));
  1736. try {
  1737. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  1738. } catch (const std::exception& e) {
  1739. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  1740. modeStr, e.what());
  1741. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  1742. }
  1743. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  1744. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  1745. }
  1746. }
  1747. // File settings
  1748. if (db.contains("files")) {
  1749. auto& files = db["files"];
  1750. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  1751. // v2.8.0 — this interval now drives the file EXPIRY sweep as well
  1752. // as orphan cleanup, so accept the plainer name too. The original
  1753. // key kept working; nothing read either of them before 2.8.0
  1754. // because there was no sweeper thread at all.
  1755. config.fileCleanupIntervalSec =
  1756. files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  1757. config.fileCleanupIntervalSec =
  1758. files.value("cleanup_interval_sec", config.fileCleanupIntervalSec);
  1759. // v2.8.0 — default retention per file type. The analogue of a
  1760. // collection's defaultTtlSeconds, so retention is an operator
  1761. // setting rather than something every uploader must remember.
  1762. //
  1763. // "default_ttl_seconds": {
  1764. // "acme:generated": 86400, // one project, one type
  1765. // "generated": 604800, // any project
  1766. // "acme:*": 2592000, // every type in one project
  1767. // "*": 0 // everything (0 = keep)
  1768. // }
  1769. if (files.contains("default_ttl_seconds") &&
  1770. files["default_ttl_seconds"].is_object()) {
  1771. for (const auto& [k, v] : files["default_ttl_seconds"].items()) {
  1772. if (v.is_number_unsigned()) {
  1773. config.fileDefaultTtlByType[k] = v.get<uint32_t>();
  1774. }
  1775. }
  1776. }
  1777. if (files.contains("allowed_types")) {
  1778. for (const auto& type : files["allowed_types"]) {
  1779. config.allowedFileTypes.push_back(type.get<std::string>());
  1780. }
  1781. }
  1782. }
  1783. // Encryption settings
  1784. if (db.contains("encryption")) {
  1785. auto& encryption = db["encryption"];
  1786. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  1787. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  1788. std::string keyFile = encryption.value("key_file", "");
  1789. if (keyFile.find("${HOME}") != std::string::npos) {
  1790. const char* home = std::getenv("HOME");
  1791. if (home) {
  1792. size_t pos = keyFile.find("${HOME}");
  1793. keyFile.replace(pos, 7, home);
  1794. }
  1795. }
  1796. config.keyFilePath = keyFile;
  1797. }
  1798. // Replication settings
  1799. if (db.contains("replication")) {
  1800. auto& replication = db["replication"];
  1801. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  1802. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  1803. if (replication.contains("peers")) {
  1804. for (const auto& peer : replication["peers"]) {
  1805. config.peerAddresses.push_back(peer.get<std::string>());
  1806. }
  1807. }
  1808. }
  1809. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  1810. if (db.contains("grpc")) {
  1811. const auto& grpc = db["grpc"];
  1812. config.grpc.maxReceiveMessageSizeMb =
  1813. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  1814. config.grpc.maxSendMessageSizeMb =
  1815. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  1816. config.grpc.resourceQuotaMemoryMb =
  1817. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  1818. config.grpc.maxConcurrentSubscribeStreams =
  1819. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  1820. config.grpc.maxConcurrentFileStreams =
  1821. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  1822. }
  1823. }
  1824. // v2.4 back-compat shim. If no listeners[] was provided, synthesize
  1825. // one from the legacy bind_address + rpc_port fields. This is what
  1826. // every existing v2.3 deployment will hit on first v2.4 boot —
  1827. // their configs don't know about listeners[] yet, and they get
  1828. // exactly the same listener they had before.
  1829. if (config.listeners.empty()) {
  1830. ListenerConfig legacy;
  1831. legacy.bind = config.bindAddress;
  1832. legacy.port = config.rpcPort;
  1833. legacy.tls.enabled = false;
  1834. legacy.auth.required = false;
  1835. config.listeners.push_back(std::move(legacy));
  1836. }
  1837. return config;
  1838. }
  1839. void DatabaseService::setupComponents() {
  1840. // v2.3 multi-project storage substrate.
  1841. //
  1842. // Each project lives at `<dataDir>/projects/<name>/env/`. The default
  1843. // project always exists and is what v2.0-v2.2 clients (which don't
  1844. // address projects) implicitly use.
  1845. //
  1846. // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
  1847. // path. migrateLegacyEnvToDefaultProject() detects that layout and
  1848. // atomically moves it under `projects/default/env/` before the
  1849. // registry opens.
  1850. migrateLegacyEnvToDefaultProject();
  1851. try {
  1852. constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
  1853. constexpr uint32_t kMaxDbs = 1024;
  1854. projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
  1855. config_.dataDirectory / "projects", kMapSize, kMaxDbs);
  1856. const auto opened = projects_->openExisting();
  1857. spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
  1858. opened.size(),
  1859. [&opened]() {
  1860. std::string s;
  1861. for (size_t i = 0; i < opened.size(); ++i) {
  1862. if (i) s += ", ";
  1863. s += opened[i];
  1864. }
  1865. return s;
  1866. }());
  1867. } catch (const std::exception& e) {
  1868. spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
  1869. "service cannot start without LMDB; bailing",
  1870. (config_.dataDirectory / "projects").string(), e.what());
  1871. projects_.reset();
  1872. throw;
  1873. }
  1874. // Create memory store with eviction config
  1875. MemoryStore::Config storeConfig;
  1876. storeConfig.nodeId = config_.nodeId;
  1877. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  1878. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  1879. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  1880. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  1881. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  1882. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  1883. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  1884. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  1885. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  1886. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  1887. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  1888. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  1889. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  1890. storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
  1891. // v2.11.0 close-out — TTL sweep budgets (storage.ttl).
  1892. storeConfig.ttlMaxCandidatesPerSweep = config_.ttlMaxCandidatesPerSweep;
  1893. storeConfig.ttlMaxBlockedRetriesPerSweep = config_.ttlMaxBlockedRetriesPerSweep;
  1894. storeConfig.ttlBlockedRetrySweeps = config_.ttlBlockedRetrySweeps;
  1895. storeConfig.ttlBlockedSummarySweeps = config_.ttlBlockedSummarySweeps;
  1896. store_ = std::make_unique<MemoryStore>(storeConfig);
  1897. // Create view manager (cache loaded in initialize() after persistence recovery)
  1898. view_manager_ = std::make_unique<ViewManager>(*store_);
  1899. // Create per-collection config manager and attach it to the store so the
  1900. // write paths route document timestamp stamps through it.
  1901. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  1902. // v2.8.0 — access policy. Constructed here; its cache is loaded after
  1903. // recovery alongside the view and collection-config caches.
  1904. policy_manager_ = std::make_unique<PolicyManager>(*store_);
  1905. // v2.11.0 T6a — relation declarations. Constructed here; its cache is
  1906. // loaded after recovery alongside the view/config/policy caches.
  1907. relation_manager_ = std::make_unique<RelationManager>(*store_);
  1908. store_->setConfigManager(config_manager_.get());
  1909. // v1.9.0 — disk-resident version history. Replaces the in-heap
  1910. // `CollectionData::versionHistory` deques that were the dominant
  1911. // source of the Zoe untracked-RSS gap. One file per collection at
  1912. // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
  1913. // here, wired into the store immediately so snapshot deserializer
  1914. // can migrate pre-v1.9 in-memory history blocks straight to disk.
  1915. HistoryStore::Config histConfig;
  1916. histConfig.dataDir = config_.dataDirectory;
  1917. history_store_ = std::make_unique<HistoryStore>(histConfig);
  1918. store_->setHistoryStore(history_store_.get());
  1919. // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
  1920. // resolver. Every write that flows through store_ commits to the
  1921. // right per-project LMDB env BEFORE the per-collection lock releases.
  1922. if (projects_) {
  1923. auto* registry = projects_.get();
  1924. store_->setDocumentStoreMirror(
  1925. [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
  1926. return registry->getOrCreate(project);
  1927. },
  1928. &mirror_healthy_,
  1929. &mirror_drift_count_);
  1930. mirror_pending_ = std::make_unique<smartbotic::db::storage::MirrorPendingLog>(
  1931. std::filesystem::path(config_.dataDirectory) / "mirror-pending.log");
  1932. store_->setMirrorFailureSink([this](const std::string& collection, const std::string& id) {
  1933. recordMirrorFailure(collection, id);
  1934. });
  1935. }
  1936. // Create persistence manager. Start from any persistenceConfig values the
  1937. // caller (config loader / CLI parser) has already populated — including
  1938. // recoveryMode — and overlay the top-level convenience fields.
  1939. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  1940. persistConfig.dataDir = config_.dataDirectory;
  1941. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  1942. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  1943. persistConfig.compressionEnabled = config_.compressionEnabled;
  1944. persistConfig.nodeId = config_.nodeId;
  1945. // Mirror the resolved recoveryMode back into our Config so downstream code
  1946. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  1947. // without having to reach into the PersistenceManager.
  1948. config_.persistenceConfig = persistConfig;
  1949. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  1950. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  1951. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  1952. const std::optional<Document>& doc, EventType eventType,
  1953. const std::optional<std::string>& actor) {
  1954. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  1955. // sequence and record it on the store so eviction stubs can carry
  1956. // a real seq (instead of doc.version, which was useless as a
  1957. // `fromSequence` hint and forced a full WAL scan on every fault).
  1958. uint64_t walSeq = 0;
  1959. switch (eventType) {
  1960. case EventType::INSERT:
  1961. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  1962. break;
  1963. case EventType::UPDATE:
  1964. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  1965. break;
  1966. case EventType::DELETE:
  1967. persistence_->logDelete(collection, id);
  1968. break;
  1969. default:
  1970. break;
  1971. }
  1972. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  1973. store_->recordWalSequence(collection, id, walSeq);
  1974. }
  1975. // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
  1976. // that it runs UNDER the per-collection write lock. That closes the
  1977. // race window where readers could see a doc in MemoryStore but not
  1978. // yet in LMDB. The callback now does only WAL + replication + events.
  1979. // v2.11.0 T12 review (C2) — replication + events extracted into
  1980. // notifyReplicationAndEvents() so relations/relation_cascade.cpp can
  1981. // drive them explicitly too. See that method's doc comment.
  1982. notifyReplicationAndEvents(collection, id, doc, eventType, actor);
  1983. });
  1984. // Set up document load callback for LRU eviction recovery.
  1985. //
  1986. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  1987. // callback below at append time, not the per-doc version counter).
  1988. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  1989. // returns entries with seq >= walSequence — the doc's last write is
  1990. // exactly at walSequence, so the very first hit is the one we want.
  1991. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  1992. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  1993. store_->setDocumentLoadCallback([this](const std::string& collection,
  1994. const std::string& id,
  1995. uint64_t walSequence) -> std::optional<Document> {
  1996. // v2.21.0 - LMDB first. The WAL scan below finds an evicted document
  1997. // only while the WAL still holds its last write; a snapshot truncates
  1998. // that, so a document still evicted at the NEXT snapshot could not be
  1999. // read and was written as absent ("will be missing from the
  2000. // snapshot"). The next boot then came up without it while LMDB still
  2001. // had it: 7,219 such rows on one production instance. LMDB holds
  2002. // every write to an evicted document (a write reloads it first), so it
  2003. // is the right source while the mirror is healthy with no drift; the
  2004. // WAL stays the fallback for system collections and a degraded mirror.
  2005. if (projects_ && mirror_healthy_.load(std::memory_order_relaxed) &&
  2006. mirror_drift_count_.load(std::memory_order_relaxed) == 0) {
  2007. try {
  2008. const auto pc = smartbotic::database::parseProjectCollection(collection);
  2009. if (!pc.collection.empty() && pc.collection.front() != '_') {
  2010. if (auto* ds = docStore(pc.project)) {
  2011. if (auto doc = ds->get(pc.collection, id)) {
  2012. doc->collection = collection;
  2013. return doc;
  2014. }
  2015. }
  2016. }
  2017. } catch (const std::exception& e) {
  2018. spdlog::warn("evicted {}/{}: LMDB read failed ({}); trying the WAL",
  2019. collection, id, e.what());
  2020. }
  2021. }
  2022. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  2023. return persistence_->loadDocument(collection, id, fromSequence);
  2024. });
  2025. // Create encryption manager
  2026. EncryptionManager::Config encryptConfig;
  2027. encryptConfig.enabled = config_.encryptionEnabled;
  2028. encryptConfig.keyFilePath = config_.keyFilePath;
  2029. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  2030. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  2031. // Create event manager
  2032. EventManager::Config eventConfig;
  2033. eventConfig.nodeId = config_.nodeId;
  2034. events_ = std::make_unique<EventManager>(eventConfig);
  2035. // Create file manager
  2036. FileManager::Config fileConfig;
  2037. fileConfig.filesDir = config_.dataDirectory / "files";
  2038. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  2039. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  2040. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  2041. fileConfig.defaultTtlSecondsByType = config_.fileDefaultTtlByType;
  2042. files_ = std::make_unique<FileManager>(fileConfig);
  2043. // Create replication manager
  2044. ReplicationManager::Config replConfig;
  2045. replConfig.nodeId = config_.nodeId;
  2046. replConfig.peerAddresses = config_.peerAddresses;
  2047. replConfig.conflictResolution = config_.conflictResolution;
  2048. replication_ = std::make_unique<ReplicationManager>(replConfig);
  2049. // Wire replication entry apply callback
  2050. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  2051. applyReplicatedEntry(entry);
  2052. });
  2053. // Create gRPC implementations
  2054. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  2055. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
  2056. *policy_manager_, *relation_manager_
  2057. );
  2058. // v2.7.0 — hand the impl the union of every listener's keys so it can
  2059. // resolve a principal per call. A token is only accepted if some listener's
  2060. // auth processor accepted it, so the union cannot widen authentication; it
  2061. // only names what was already authenticated.
  2062. {
  2063. std::vector<smartbotic::database::auth::PrincipalResolver::NamedKey> all;
  2064. for (const auto& l : config_.listeners) {
  2065. for (const auto& k : l.auth.keys) all.push_back({k.name, k.key});
  2066. }
  2067. storageImpl_->setPrincipalKeys(std::move(all));
  2068. }
  2069. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  2070. storageImpl_->setStreamLimits(
  2071. config_.grpc.maxConcurrentSubscribeStreams,
  2072. config_.grpc.maxConcurrentFileStreams);
  2073. storageImpl_->setMaxSendBytes(
  2074. static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024); // v2.13.0
  2075. // v2.13.1 - a stored row must stay readable: the largest body a write may
  2076. // leave behind is the send limit less room for metadata and a vector sent
  2077. // alongside (16 KB at dimension 4096). Enforced on insert/update/upsert/
  2078. // batch bodies and on the RESULT of a patch.
  2079. {
  2080. constexpr size_t kReadMargin = 256 * 1024;
  2081. const size_t send = static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024;
  2082. store_->setMaxDocumentBytes(send > 2 * kReadMargin ? send - kReadMargin : send / 2);
  2083. }
  2084. // v2.16.0 - collection schemas. The check sees the body as the store holds
  2085. // it, so it validates a copy: read metadata and `_vector` removed (neither
  2086. // is a user field), sensitive fields decrypted (a rule about a value must
  2087. // judge the value, not its ciphertext).
  2088. store_->setSchemaCheck([this](const std::string& collection, const nlohmann::json& body) {
  2089. auto entry = schemas_.get(CollectionConfigManager::canonicalKey(collection));
  2090. if (!entry) return;
  2091. const nlohmann::json copy = schemaView(body);
  2092. size_t total = 0;
  2093. auto violations = entry->compiled->validate(copy, 10, &total);
  2094. if (violations.empty()) return;
  2095. const std::string summary = smartbotic::db::schema::summarize(violations, total);
  2096. if (entry->audit) {
  2097. // Rate-limited: an audit run on a busy collection must not flood
  2098. // the log. The counter is exact.
  2099. const uint64_t n = entry->auditViolations.fetch_add(1) + 1;
  2100. if (n <= 20 || (n & (n - 1)) == 0) {
  2101. spdlog::warn("v2.16 schema AUDIT: a write to {} does not conform ({} so far): {}",
  2102. collection, n, summary);
  2103. }
  2104. return;
  2105. }
  2106. entry->refusals.fetch_add(1);
  2107. std::vector<std::string> paths;
  2108. for (const auto& v : violations) paths.push_back(v.path);
  2109. throw SchemaViolation(collection, "schema violation: " + summary, std::move(paths));
  2110. });
  2111. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  2112. *store_, *replication_, *persistence_
  2113. );
  2114. }
  2115. void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
  2116. const std::string& id,
  2117. const std::optional<Document>& doc,
  2118. EventType eventType,
  2119. const std::optional<std::string>& actor) {
  2120. // Queue for replication broadcast
  2121. if (replication_ && config_.replicationEnabled) {
  2122. databasepb::ReplicationEntry entry;
  2123. entry.set_collection(collection);
  2124. entry.set_document_id(id);
  2125. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  2126. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  2127. // is now treated by receivers as "legacy / unknown origin".
  2128. entry.set_node_id(config_.nodeId);
  2129. entry.set_global_timestamp(
  2130. std::chrono::duration_cast<std::chrono::milliseconds>(
  2131. std::chrono::system_clock::now().time_since_epoch()
  2132. ).count());
  2133. switch (eventType) {
  2134. case EventType::INSERT:
  2135. entry.set_op(databasepb::OP_INSERT);
  2136. // Send the full Document envelope (id, collection, data,
  2137. // version, timestamps, encryption state). The follower's
  2138. // applyReplicatedEntry uses Document::fromJson() which
  2139. // expects this envelope — sending only doc->data silently
  2140. // dropped every user field on the other side.
  2141. if (doc) entry.set_data(doc->toJson().dump());
  2142. break;
  2143. case EventType::UPDATE:
  2144. entry.set_op(databasepb::OP_UPDATE);
  2145. if (doc) entry.set_data(doc->toJson().dump());
  2146. break;
  2147. case EventType::DELETE:
  2148. entry.set_op(databasepb::OP_DELETE);
  2149. break;
  2150. default:
  2151. break;
  2152. }
  2153. replication_->queueForReplication(entry);
  2154. }
  2155. // Publish event
  2156. if (events_) {
  2157. DatabaseEvent event;
  2158. event.type = eventType;
  2159. event.collection = collection;
  2160. event.documentId = id;
  2161. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  2162. std::chrono::system_clock::now().time_since_epoch()
  2163. ).count();
  2164. event.nodeId = config_.nodeId;
  2165. if (actor) {
  2166. event.actor = *actor;
  2167. } else if (doc) {
  2168. event.actor = doc->updatedBy;
  2169. }
  2170. if (doc) {
  2171. event.data = doc->data();
  2172. }
  2173. events_->publish(event);
  2174. }
  2175. }
  2176. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  2177. try {
  2178. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  2179. // with the originating node's id. This is what makes follower-side
  2180. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  2181. // replicated documents. Echo amplification is prevented by:
  2182. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  2183. // - SyncProtocol skipping entries whose origin is the peer itself
  2184. // both implemented in the same v1.8.0 cycle.
  2185. const std::string origin = entry.node_id().empty()
  2186. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  2187. : entry.node_id();
  2188. switch (entry.op()) {
  2189. case databasepb::OP_INSERT:
  2190. case databasepb::OP_UPDATE:
  2191. case databasepb::OP_UPSERT: {
  2192. if (entry.data().empty()) {
  2193. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  2194. return;
  2195. }
  2196. auto json = smartbotic::db::parse_to_nlohmann(entry.data());
  2197. Document doc = Document::fromJson(json);
  2198. doc.id = entry.document_id();
  2199. doc.nodeId = entry.node_id();
  2200. // loadDocument bypasses the persist-and-broadcast callback to avoid
  2201. // re-replicating; we explicitly write to the WAL right after with
  2202. // the origin-aware overload so eviction/WAL recovery still works.
  2203. store_->loadDocument(entry.collection(), doc);
  2204. // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
  2205. // MemoryStore persist callback that normally drives the
  2206. // dual-write mirror; in v2.0-v2.2 the mirror was a side
  2207. // channel and reads still hit MemoryStore, so the bypass
  2208. // was harmless. In v2.3 reads are LMDB-first, so a
  2209. // follower that only filled MemoryStore would return
  2210. // empty Find/Get for every replicated doc. Route the
  2211. // entry through the same project-aware mirror the write
  2212. // handlers use.
  2213. if (projects_) {
  2214. auto pc = smartbotic::database::parseProjectCollection(
  2215. entry.collection());
  2216. if (auto* ds = projects_->getOrCreate(pc.project)) {
  2217. std::optional<Document> opt_doc(doc);
  2218. const uint64_t drift_before =
  2219. mirror_drift_count_.load(std::memory_order_relaxed);
  2220. struct RecordOnDrift { // v2.21.0 - however the block exits
  2221. DatabaseService* self; const std::string& c; const std::string& id;
  2222. uint64_t before;
  2223. ~RecordOnDrift() {
  2224. if (self->mirror_drift_count_.load(std::memory_order_relaxed) > before)
  2225. self->recordMirrorFailure(c, id);
  2226. }
  2227. } recordOnDrift{this, entry.collection(), doc.id, drift_before};
  2228. try {
  2229. smartbotic::db::storage::applyDualWriteMirror(
  2230. ds, mirror_healthy_, mirror_drift_count_,
  2231. pc.collection, doc.id, opt_doc, EventType::INSERT);
  2232. } catch (const smartbotic::db::storage::UniqueViolation& e) {
  2233. // v2.11.0 T11 finding 1 — deliberate choice, not an
  2234. // accident of the generic catch below. By this
  2235. // point store_->loadDocument() above has ALREADY
  2236. // put the row into MemoryStore (loadDocument
  2237. // bypasses the persist callback specifically to
  2238. // avoid re-replicating), so unlike every
  2239. // client-facing write path there is no "reject the
  2240. // whole operation" available: the origin node
  2241. // already committed this write and every other
  2242. // follower is expected to converge to it too.
  2243. // Undoing loadDocument here would silently diverge
  2244. // this follower's data from the rest of the
  2245. // cluster over a constraint that may not even
  2246. // exist on the origin (this follower could have
  2247. // declared the unique field locally, after the
  2248. // fact — replication carries no guarantee the
  2249. // origin shares this node's config). So
  2250. // MemoryStore keeps the row — it is the true
  2251. // record of what replication decided — and the
  2252. // mirror is marked unhealthy ON PURPOSE: this is
  2253. // exactly the pre-T11 swallow-and-flip outcome,
  2254. // chosen deliberately for this one caller so an
  2255. // operator sees the drift (and LMDB-first reads
  2256. // fall back to MemoryStore, which has the answer)
  2257. // rather than nothing signalling a permanent gap
  2258. // between the two stores.
  2259. spdlog::error(
  2260. "v2.11 replication: unique constraint violated applying "
  2261. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  2262. "marking the mirror unhealthy so reads fall back instead "
  2263. "of silently disagreeing with MemoryStore",
  2264. entry.collection(), doc.id, e.what());
  2265. mirror_healthy_.store(false, std::memory_order_release);
  2266. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  2267. } catch (const smartbotic::db::storage::MissingParentReference& e) {
  2268. // v2.11.0 T13 — same deliberate swallow-and-flip as
  2269. // the UniqueViolation catch just above, for the same
  2270. // reason: loadDocument() has already committed this
  2271. // row into MemoryStore, the origin already accepted
  2272. // the write, and this follower may not even have the
  2273. // same validate_on_write declaration (or the same
  2274. // parent data) as the origin did at the time it
  2275. // wrote. MemoryStore keeps the row; the mirror is
  2276. // marked unhealthy on purpose so an operator sees
  2277. // the drift and reads fall back to MemoryStore
  2278. // rather than the two stores silently disagreeing.
  2279. spdlog::error(
  2280. "v2.11 replication: validate_on_write rejected applying "
  2281. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  2282. "marking the mirror unhealthy so reads fall back instead "
  2283. "of silently disagreeing with MemoryStore",
  2284. entry.collection(), doc.id, e.what());
  2285. mirror_healthy_.store(false, std::memory_order_release);
  2286. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  2287. }
  2288. }
  2289. }
  2290. if (persistence_) {
  2291. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  2292. ? persistence_->logInsert(entry.collection(), doc, origin)
  2293. : persistence_->logUpdate(entry.collection(), doc, origin);
  2294. if (walSeq > 0) {
  2295. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  2296. }
  2297. }
  2298. spdlog::trace("Applied replicated {} to {}/{} from {}",
  2299. entry.op() == databasepb::OP_INSERT ? "insert" :
  2300. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  2301. entry.collection(), entry.document_id(), entry.node_id());
  2302. break;
  2303. }
  2304. case databasepb::OP_DELETE: {
  2305. store_->remove(entry.collection(), entry.document_id());
  2306. if (persistence_) {
  2307. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  2308. }
  2309. spdlog::trace("Applied replicated delete to {}/{} from {}",
  2310. entry.collection(), entry.document_id(), entry.node_id());
  2311. break;
  2312. }
  2313. case databasepb::OP_CREATE_COLLECTION: {
  2314. CollectionOptions options;
  2315. store_->createCollection(entry.collection(), options);
  2316. if (persistence_) {
  2317. persistence_->logCreateCollection(entry.collection(), options, origin);
  2318. }
  2319. spdlog::trace("Applied replicated create collection {} from {}",
  2320. entry.collection(), entry.node_id());
  2321. break;
  2322. }
  2323. case databasepb::OP_DROP_COLLECTION: {
  2324. store_->dropCollection(entry.collection());
  2325. if (persistence_) {
  2326. persistence_->logDropCollection(entry.collection(), origin);
  2327. }
  2328. spdlog::trace("Applied replicated drop collection {} from {}",
  2329. entry.collection(), entry.node_id());
  2330. break;
  2331. }
  2332. default:
  2333. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  2334. break;
  2335. }
  2336. } catch (const std::exception& e) {
  2337. spdlog::error("Failed to apply replicated entry: {}", e.what());
  2338. }
  2339. }
  2340. void DatabaseService::startGrpcServer() {
  2341. if (config_.listeners.empty()) {
  2342. // Should never hit — parseConfig's back-compat shim always
  2343. // synthesises at least one. Defend anyway.
  2344. throw std::runtime_error("startGrpcServer: no listeners configured");
  2345. }
  2346. const int64_t mb = 1024 * 1024;
  2347. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  2348. config_.grpc.maxReceiveMessageSizeMb,
  2349. config_.grpc.maxSendMessageSizeMb,
  2350. config_.grpc.resourceQuotaMemoryMb,
  2351. config_.grpc.maxConcurrentSubscribeStreams,
  2352. config_.grpc.maxConcurrentFileStreams);
  2353. grpcServers_.reserve(config_.listeners.size());
  2354. for (const auto& listener : config_.listeners) {
  2355. const std::string addr = listener.bind + ":" + std::to_string(listener.port);
  2356. grpc::ServerBuilder builder;
  2357. // v2.4 — choose credentials per listener. Plaintext for
  2358. // tls.enabled=false; SslServerCredentials with the operator's
  2359. // cert+key (or an auto-generated self-signed pair) for true.
  2360. std::shared_ptr<grpc::ServerCredentials> creds;
  2361. if (listener.tls.enabled) {
  2362. std::filesystem::path cert_path = listener.tls.cert_path;
  2363. std::filesystem::path key_path = listener.tls.key_path;
  2364. // Resolve cert+key. If either is missing/unreadable AND
  2365. // auto_self_signed_if_missing is set, generate a pair.
  2366. const bool cert_ok = !cert_path.empty()
  2367. && std::filesystem::exists(cert_path);
  2368. const bool key_ok = !key_path.empty()
  2369. && std::filesystem::exists(key_path);
  2370. if (!cert_ok || !key_ok) {
  2371. if (!listener.tls.auto_self_signed_if_missing) {
  2372. throw std::runtime_error(
  2373. "TLS listener " + addr +
  2374. ": cert or key missing and auto_self_signed_if_missing=false");
  2375. }
  2376. const auto out_dir = config_.dataDirectory / "tls";
  2377. auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
  2378. out_dir, listener.bind);
  2379. cert_path = gen.cert_path;
  2380. key_path = gen.key_path;
  2381. spdlog::warn(
  2382. "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
  2383. "auto-generated self-signed cert at '{}' (key '{}'). "
  2384. "OK for dev. For production, drop a real cert + key at "
  2385. "the configured cert_path/key_path.",
  2386. addr,
  2387. listener.tls.cert_path.string(),
  2388. listener.tls.key_path.string(),
  2389. cert_path.string(),
  2390. key_path.string());
  2391. }
  2392. auto slurp = [](const std::filesystem::path& p) {
  2393. std::ifstream f(p);
  2394. if (!f) throw std::runtime_error("read " + p.string());
  2395. std::stringstream ss; ss << f.rdbuf();
  2396. return ss.str();
  2397. };
  2398. grpc::SslServerCredentialsOptions sslOpts;
  2399. grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
  2400. kp.private_key = slurp(key_path);
  2401. kp.cert_chain = slurp(cert_path);
  2402. sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
  2403. creds = grpc::SslServerCredentials(sslOpts);
  2404. } else {
  2405. creds = grpc::InsecureServerCredentials();
  2406. }
  2407. // v2.4 Stage D — attach the bearer-token auth processor when
  2408. // the listener requires it. The processor validates the
  2409. // `authorization: Bearer <key>` metadata against the listener's
  2410. // configured keys list. gRPC rejects with UNAUTHENTICATED
  2411. // (no per-handler code needed).
  2412. if (listener.auth.required) {
  2413. if (listener.auth.keys.empty()) {
  2414. throw std::runtime_error(
  2415. "Listener " + addr + ": auth.required=true but auth.keys is empty");
  2416. }
  2417. // v2.7.0 — a key name is a principal, so it must be unambiguous.
  2418. // Refuse at startup rather than resolving a policy against a name
  2419. // that means two different callers.
  2420. {
  2421. std::set<std::string> seen;
  2422. for (const auto& k : listener.auth.keys) {
  2423. if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
  2424. smartbotic::database::auth::isReservedPrincipal(k.name)) {
  2425. throw std::runtime_error(
  2426. "Listener " + addr + ": auth key name '" + k.name +
  2427. "' is reserved. `anonymous` denotes an unauthenticated "
  2428. "caller and `unnamed` denotes a legacy bare key; a real "
  2429. "key must not be able to impersonate either in a policy.");
  2430. }
  2431. if (!seen.insert(k.name).second &&
  2432. k.name != smartbotic::database::auth::kPrincipalUnnamed) {
  2433. throw std::runtime_error(
  2434. "Listener " + addr + ": duplicate auth key name '" +
  2435. k.name + "'. A principal must identify one caller, "
  2436. "otherwise a policy written against it is ambiguous.");
  2437. }
  2438. }
  2439. }
  2440. if (!listener.tls.enabled) {
  2441. // gRPC ABORTS the process if an auth metadata processor is
  2442. // attached to insecure credentials
  2443. // (insecure_server_credentials.cc: "assertion failed: 0").
  2444. // This used to be a WARN, which meant a plaintext+auth listener
  2445. // looked merely inadvisable in the config and then killed the
  2446. // server on start with an unexplained assert. Refuse it here
  2447. // with a message that says what to do instead.
  2448. throw std::runtime_error(
  2449. "Listener " + addr + ": auth.required=true requires "
  2450. "tls.enabled=true. gRPC does not support an auth metadata "
  2451. "processor on insecure credentials and will abort the "
  2452. "process. Enable TLS for this listener (set "
  2453. "tls.auto_self_signed_if_missing for a local dev cert), or "
  2454. "drop auth and rely on binding to loopback.");
  2455. }
  2456. std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
  2457. nk.reserve(listener.auth.keys.size());
  2458. for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
  2459. creds->SetAuthMetadataProcessor(
  2460. std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
  2461. std::move(nk)));
  2462. }
  2463. builder.AddListeningPort(addr, creds);
  2464. builder.RegisterService(storageImpl_.get());
  2465. builder.RegisterService(replicationImpl_.get());
  2466. builder.SetMaxReceiveMessageSize(
  2467. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  2468. builder.SetMaxSendMessageSize(
  2469. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  2470. grpc::ResourceQuota quota("smartbotic-db-" + addr);
  2471. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  2472. builder.SetResourceQuota(quota);
  2473. auto server = builder.BuildAndStart();
  2474. if (!server) {
  2475. throw std::runtime_error("Failed to start gRPC server on " + addr);
  2476. }
  2477. // v2.4 Stage B log line — listener identity printed so operators
  2478. // know exactly which interface is exposed with which policy.
  2479. // Stage C/D will extend with TLS + auth status.
  2480. spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
  2481. addr,
  2482. listener.tls.enabled ? "true" : "false",
  2483. listener.auth.required ? "true" : "false");
  2484. grpcServers_.push_back(std::move(server));
  2485. }
  2486. }
  2487. void DatabaseService::stopGrpcServer() {
  2488. // ⚠ Shutdown() WITHOUT a deadline waits for every in-flight RPC to return,
  2489. // and it does NOT cancel them. `Subscribe` never returns on its own: its
  2490. // handler parks in `while (!context->IsCancelled())`, and that context is
  2491. // cancelled only when the client goes away or a shutdown DEADLINE expires.
  2492. // So a single connected subscriber - the normal state of any consumer using
  2493. // events - hung this call forever.
  2494. //
  2495. // The cost is not just a slow stop. `stop()` calls this FIRST and takes the
  2496. // final snapshot AFTER it, so the hang blocked the snapshot; systemd then
  2497. // SIGKILLed at TimeoutStopSec=300, and the next boot recovered by WAL-only
  2498. // replay, which trips auto read-only mode and needs an operator `unlock`.
  2499. // A graceful restart therefore looked like a crash to the next boot.
  2500. //
  2501. // With a deadline, gRPC cancels whatever is still running once it expires,
  2502. // the Subscribe loops observe IsCancelled() and unwind, and shutdown
  2503. // proceeds. The deadline is ABSOLUTE and shared across listeners, so the
  2504. // total wait is bounded by the grace period rather than by
  2505. // grace × listener count.
  2506. //
  2507. // Five seconds: long enough for an ordinary unary RPC in flight to finish
  2508. // (they are milliseconds), short enough that it is invisible next to the
  2509. // final snapshot, which is the part of shutdown that legitimately takes
  2510. // time (~70 s on the largest known dataset).
  2511. // v2.11.2 — tell the parked streaming handlers to return BEFORE asking gRPC
  2512. // to shut down. Subscribe has no work of its own; it waits for the stream to
  2513. // end. Without this signal it learned of the stop only when the deadline
  2514. // below expired and gRPC cancelled it, so every stop paid the full grace
  2515. // period. With it, the streams are usually gone before Shutdown is even
  2516. // called and the deadline is what it should be: a backstop, not the
  2517. // mechanism.
  2518. if (storageImpl_) {
  2519. storageImpl_->beginShutdown();
  2520. }
  2521. constexpr auto kShutdownGrace = std::chrono::seconds(5);
  2522. const auto deadline = std::chrono::system_clock::now() + kShutdownGrace;
  2523. for (auto& server : grpcServers_) {
  2524. if (server) server->Shutdown(deadline);
  2525. }
  2526. grpcServers_.clear();
  2527. }
  2528. } // namespace smartbotic::database