Status and remaining work live in
docs/ROADMAP.md- read it before planning anything. This file records per-release behaviour and hard-won lessons; it does not track what is left to do.Docs hygiene: plans under
docs/superpowers/plans/are pending work; anything inplans/archive/has already shipped and must not be executed. Specs carry a status banner. Resolved incidents are indocs/incidents/.
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)
⚠ Pass -DCMAKE_BUILD_TYPE explicitly. Without it CMake picks no build type and
produces an unoptimised binary that behaves materially differently from the
released one — timing-sensitive tests can pass at -O2 and fail at -O0. Three
separate measurements of test_eviction disagreed for exactly this reason before
anyone noticed the two build trees were configured differently.
packaging/dev.shA host without the yyjson/lmdb development packages, or with a protobuf/gRPC that differs from the release target, cannot run the commands above. Use the build image instead - the same one the packages are made in:
packaging/dev.sh build # configure if needed, build into ./build
packaging/dev.sh test # ctest
packaging/dev.sh test -R relation # ctest args pass through
packaging/dev.sh e2e # list tests/load_test suites
packaging/dev.sh e2e test_relations test_indexes
packaging/dev.sh e2e all
packaging/dev.sh run ./build/cli/smartbotic-db-cli --version
packaging/dev.sh shell
It mounts the checkout at the same absolute path it has on the host, so
build/ means the same thing inside and outside the container and works
wherever the checkout lives. Do not mount it at a fixed path: a build tree
configured for a path that exists only in a container confuses every host tool
that reads it, and a host cmake --build build then creates that phantom
directory. build.sh --local (which dev.sh build runs) notices a build/
that was configured elsewhere, or by another system's CMake, and reconfigures
it from scratch rather than failing with CMake's unhelpful error.
build/ holds whichever system built it last. Do not alternate host and
container builds against it; pick one.
cmake --build build -j$(nproc) && ./build/tests/test_vector_storage
proto/database.proto — gRPC service and message definitionsservice/src/ — Database server implementation
memory_store.hpp/.cpp — In-memory document + vector storagedocument.hpp — Document and CollectionOptions typesdatabase_grpc_impl.cpp — gRPC request handlerspersistence/ — WAL, snapshots, persistence managermigrations/ — Migration runnerclient/ — C++ client library (smartbotic-db-client)tests/ — Integration testsSimilaritySearch RPC. Vectors use _vector document field, stored in parallel float arrays, persisted through WAL (VEC_PUT/VEC_DELETE) and snapshots (v3 format). Collection vector_dimension option is immutable after creation.PatchDocument RPC merges fields into existing documents atomically (server-side, within collection lock). Client patch() method. update() uses automatic optimistic locking with retry. See docs/integration-guide.md for concurrency patterns._views system collection, created via create_view migration op or createView RPC. Writes on view names are rejected.timestamp_precision config ("ms" default, "ns" for rapid-write collections). Stamps _created_at/_updated_at at the configured resolution, cached hot-path lookup. configureCollection RPC flips the config atomically; migrateCollectionTimestamps RPC converts existing data during maintenance windows (idempotent via 10^15 threshold)..tmp + fsync + rename + post-write verification), loader fallback chain across snapshots, MySQL-style recovery modes (normal / snapshot_fallback / wal_only / best_effort / force_empty) selectable via --recovery-mode flag or recovery.mode config. Non-trivial recovery (fallback, WAL-only, forced empty) automatically enters read-only mode — operator must smartbotic-db-cli unlock or pass --force-readwrite to accept writes. Exit code 10 when recovery is refused.ResourceQuota + per-RPC-type stream limits (Subscribe, UploadFile, DownloadFile). Configurable under storage.grpc. Excess streams get RESOURCE_EXHAUSTED with operator log./etc/smartbotic-database/conf.d/*.json deep-merges over config.json using RFC 7396 semantics (arrays replace, objects merge). Lets consumer debs ship tuned settings without touching the upstream conffile. Strict on syntax errors (exit 11), lenient on unknown keys.eviction_chunk_size=1000, eviction_chunk_pause_ms=50, hot_write_floor_ms=30000. Four pressure levels (normal/soft/hard/emergency) gate behavior: soft = trickle, hard = aggressive + MEMORY_PRESSURE_HIGH event, emergency = admission control rejects writes with RESOURCE_EXHAUSTED. Per-collection memory_priority (low/normal/high) biases selection. Quiesce skips docs with in-flight writes. WAL-fallback no longer holds per-collection mutex during disk I/O.Client::getMemoryStats() returns per-collection stats + pressure level. Client library auto-retries write RPCs on DEADLINE_EXCEEDED/RESOURCE_EXHAUSTED/UNAVAILABLE with exponential backoff + jitter (writeRetries=3, writeRetryBackoffMs=100). Reads are not auto-retried.apt upgrade smartbotic-database runs a preinst hook that snapshots /var/lib/smartbotic-database/ to /var/backups/smartbotic-database/pre-upgrade-<ts>-from-<version>/ via cp -a after the old prerm stops the service. Retention 3, 1.2× free-space precheck on the backup volume (aborts the upgrade if short). Opt out with SMARTBOTIC_DB_SKIP_BACKUP=1 apt upgrade. Tunables: SMARTBOTIC_DB_BACKUP_RETENTION, SMARTBOTIC_DB_BACKUP_ROOT.smartbotic::db::parse_to_nlohmann (yyjson-backed) instead of nlohmann::json::parse. Measured 2.80× speedup on Zoe-shape corpora (136ms→49ms on 10k docs). In-memory representation stays nlohmann::json until Phase B. Wire and on-disk JSON bytes unchanged. New runtime dep: libyyjson0. Bench: ./build/tests/bench_json_parse <corpus.jsonl>.Document::data is now a smartbotic::db::doc_binary::Doc (yyjson mut_doc wrapper) with a lazy nlohmann::json view cache. New accessor surface: doc.field(name) is the O(field-count) fast-path that reads one top-level field without materialising the full tree (the dominant read pattern), doc.data() is the lazy full-tree accessor, doc.set_data(j) re-encodes from an nlohmann tree. Wire and on-disk JSON bytes unchanged. Honest note: per-doc heap footprint is ~1.5% smaller than v1.10 (1618→1594 bytes on Zoe-shape) — the win is field-access CPU + Phase C scaffolding, not RSS. See docs/superpowers/specs/2026-05-15-binary-doc-format-decision.md post-implementation amendment for the bench numbers. Bench: ./build/tests/bench_doc_memory --mode=<nlohmann|binary> [N].ListFiles.total_count reported the PAGE, not the total. The policy work set it to response->files_size() to avoid leaking counts of files a principal cannot see; with limit=5 on an 865-file project it reported 5, so file paging was impossible. Now: unfiltered total when no project is secured (free, and the case for every deployment today), recount over the whole matching set when one is. has_more derives from the same number. (2) ViewManager::loadFromStore truncated at 100 views — a bare Query and Query::limit defaults to 100, so view 101+ silently did not exist and the v2.4.2 re-key migration never reached it. Same trap as PolicyManager; note limit=0 returns NOTHING, not everything (end = min(offset+limit, size)). tests/test_views.cpp could never have caught it: it only exercises applyProjection() and never builds a MemoryStore, so tests/test_view_manager_paging.cpp now does (250 views, reload, spot-checks either side of the old boundary; 7 assertions fail without the fix). (3) TTL is changeable after creation, on all four axes it was previously frozen: optional uint32 ttl_seconds on UpdateRequest/PatchDocumentRequest (absent = leave alone, 0 = clear, N = N seconds from now — presence is what makes three cases expressible), Client::patchWithTtl as an ABI-safe overload; defaultTtlSeconds on an existing collection via createCollection (always safe, it only affects future inserts, and 0 is a real value not "unset"); SetFileTtl RPC + FileManager::setExpiryIn for a stored file (project-scoped, and an already-expired file cannot be resurrected by extending it); and per-fileType retention at runtime via FileManager::setDefaultTtl, persisted to <filesDir>/retention.json with write-and-rename and layered OVER the config baseline so a restart keeps it. (4) vector_dimension recovery. It was unreachable after creation — createCollection on an existing collection updated only maxVersions, and alterCollection can set it but has no RPC and zero call sites — which permanently stranded collections created through the pre-2.4.5 createCollection bug (similaritySearch returns nothing, forever). Now settable only while the collection holds no vectors, which is safe because extractVector() returns early when the dimension is 0 so no vector of a conflicting dimension can exist; refused once vectors exist. Documents already stored keep _vector embedded and are NOT indexed retroactively — rewrite them. (5) ListCollections is project-scoped, mirroring ListViewsRequest; a collection name is information about someone else's schema even when its contents are unreachable. (6) Build provenance actually works now. BUILD_GIT_COMMIT had been computed by build.sh and passed as a --build-arg since v2.4 with the ARG declared — but unlike BUILD_VERSION it was never promoted to an ENV, so nothing consumed it. --version now prints 2.8.0 (commit 51f6b6f). ctest 19/19, namespacing e2e 44/44, policy 19/19, views + TLS/auth green.listFiles carries the metadata map. Reported by smartbotic-vectorapi, who alias a served HTTP path through metadata["path"]: every listed record had an empty map while getFileInfo returned it, so a lookup by a metadata value cost one getFileInfo per row on an unauthenticated path. The store's listing reads the whole record (FileManager loader fills metadata); the ListFiles handler copied every FileInfo field except it. The client always read the field. test_file_store +2 (upload with two metadata keys, listing and info both return them); reverted: 1 fails.ReplayFileStats::missingSequences/gapRuns, counted in scanFile between consecutive records; lastSequence is now the highest seen, so a duplicate does not reopen a gap): the 2.21.5 race dropped 63 whole records from a production file and no reader saw it. The file is framed, so only the numbers show it. Worded with what it MEANS (smartbotic-vectorapi's point, after the evicted-document WARN's trailing hint had sent readers to the wrong cause): writes may have been lost from the WAL, LMDB is not affected, report it. A gap can also come from a damaged record skipped by the resync (counted in both). Test: case G in test_wal_reader_resyncs_past_damage (records 101-102 and 150 removed cleanly: 0 unreadable, a complete read, 3 missing in 2 runs). Not revert-checked (a counter whose value the test asserts). (2) Upload validation in UploadFile before anything is stored: a non-empty project failing isValidProjectName -> invalid_project; a non-empty MIME type without / -> invalid_mime_type (both INVALID_ARGUMENT, fields). Found by smartbotic: two records on the local instance had every metadata field shifted one slot (mime = the filename, project = <uuid>/output_1.png), not a proto mismatch (tags 3/5/6/9 are not consecutive, and a client fills project from its Config): some consumer's own wrapper. test_file_store +2; reverted: 2 fail (the MIME case then only meets the allow-list's mime_type_not_allowed). (3) update that drops fields is logged (warnDroppedFields in MemoryStore::update/updateIfVersion: top-level keys of the stored yyjson body absent from the new one, iterated without building a JSON tree; WARN at most once a minute per collection with a suppressed count; _ collections exempt, the server writes those whole). smartbotic's dedup node passes partial=true; one argument less and every duplicate would have wiped four fields with no trace. test_stale_memory greps the line; reverted: 1 fails. (4) storage.consistency.memory_newer: report | write (Config::consistencyMemoryNewer, unknown -> report with an ERROR): write sends the audit's memory-newer rows through syncDocStoreFromMemory; lines name the collection and count either way, summary N newer in memory (W written to LMDB, L left). Default report: smartbotic's caveat that it makes an unreviewed write authoritative. The local instance's 9 image_hashes rows were diffed field by field from the pre-upgrade copy (only seenCount/lastSeenAt, and one dangling fileId) before anyone decided. test_stale_memory boot 4 (m1 written, then read back as memory's version); reverted: 2 fail.WriteAheadLog::scanFile is now the one reader of a WAL file for replay() and open(): it mmaps the file, reads record by record (recordAt: plausible length, in bounds, WalEntry::deserialize incl. checksum), and on a record that fails starts a resync from the next byte. Cheap filters come first: op type in INSERT..VEC_DELETE, sequence above the last good one (header start - 1 or the highest seen) and within 10^8 of it. Then recordAt. Skipped regions are counted (resynced, skippedBytes); bytes after the last valid record that no resync can parse end the file (bytesRead = end of the last valid record). open()'s max-sequence scan had the same fail-stop, so damage in the CURRENT file made the sequence too low and new appends reuse numbers on disk (worse than a short replay: it corrupts the ordering everything trusts). It now goes through scanFile. And a torn tail is cut at open (resize_file to the end of the last valid record; lastOpenTruncatedBytes, WARN in recovery): a crash mid-write left a half record, and the next process appended after it, manufacturing a damaged record in the middle of the file. Caveat: a record of a FUTURE format that this binary cannot parse at the end of the current file would read as a torn tail on a downgrade. Tests (test_snapshot_durability, test_wal_reader_resyncs_past_damage, 200-entry files damaged on disk): a byte deleted inside record 50 (the production shape) loses exactly 50; a flipped byte loses exactly that record (checksum count 1); a garbage length prefix; 1,000 zeroed bytes lose exactly the records they touch; a torn tail is cut (25 bytes), the sequence continues at 199 and the next append is 200; damage in the current file before a reopen still finds sequence 200, so the next append is 201. Reverted: no resync -> 49 of 199 entries (the production amplification in miniature); no torn-tail cut -> the truncation check fails. The reopen case is not separately shown failing under the revert (the first case aborts the run first). Real-specimen check (smartbotic-vectorapi, the production file under 2.21.6-1 from apt): 192,073 records applied, 1 skipped (590 bytes at 13,862,819, the record of sequence 1,156,526), all 104,833,315 bytes read. Walking the file by length prefix closed the arithmetic: 192,072 distinct sequences + the damaged one + 63 GENUINELY ABSENT = the 192,136 span, the 63 in 46 runs of 1 or 2, plus one byte-identical DUPLICATE (1,292,596 again after 1,292,597, the one out of sequence order). So the 2.21.5 race dropped and duplicated WHOLE records as well as damaging one. ⚠ Dropped records are invisible to every reader, old or new: the file stays perfectly framed with numbers missing, so nothing reports them. The writes still reached memory and LMDB at the time; the only exposure is a row whose last write was among them, and that is the stale-memory class the version audit repairs (prod: 3 reloaded on 2.21.4, 0 since). The loud failure (one damaged record fail-stopping 160,000 healthy ones) is what led to the quiet one; without it the boots would have looked clean. Next diagnostic worth adding: report sequence GAPS per WAL file at replay.1 unreadable (1 checksum, first at byte 13,862,819), read 13,863,410 of 104,833,315 bytes, and the other two files were complete; 34,002 + 31,867 + 127,907 = the 193,776 replayed. They searched the file for the neighbouring sequence numbers as little-endian u64: every one present at ~590-byte intervals EXCEPT 1,156,526, with the record at the fault readable JSON. So ONE damaged record (one byte short of its length prefix: the next record starts at 13,863,409, the declared end was 13,863,410) and fail-stop replay discarded the 160,261 intact records behind it. Cause: WriteAheadLog::sync() called currentFile_.flush() WITHOUT writeMutex_ (the WAL sync thread every wal_sync_interval_ms, 100 ms, and flushWal() before a cascade commit) while append() wrote to the same std::ofstream under it; a std::filebuf is not thread-safe. Now the flush is under the lock and the fsync outside it, on an fd opened under the lock (so a rotation in between cannot redirect it); append()'s own syncOnWrite path calls fsyncCurrentFile() (it already holds the lock). Test test_wal_append_races_sync (4 writers x 15,000 appends while a thread calls sync() in a loop, then replay): unfixed 3 of 3 wrong (60,111 and 60,138 of 60,000 - duplicated bytes - and one with exactly the production signature, 1 unreadable, file ended early, 2,875 lost); fixed 5 of 5. Still open (ROADMAP 5g): a resynchronising reader - a damaged record costs the rest of its file; open()'s max-sequence scan has the same fail-stop, which would let a damaged CURRENT file make new appends reuse sequence numbers. (2) The audit direction. Staging 2.21.4 on our own nightly backup (graceful stop, Replayed 0) reloaded 15 rows; logging both sides showed 4 of 5 sampled were NEWER in memory (memory v3, LMDB v2/v1, August timestamps: mirror failures from before 2.21.0 recorded them), one LMDB-newer. 2.21.4's premise ("after the re-mirror and pending replay, any difference means memory is behind") is false for historical divergence, and it replaced the newer copy (reads were already showing LMDB's older one; the lost thing is a write only memory held). Now a row is reloaded only when LMDB is newer: later updatedAt (normalised to ns, ms and ns stamps coexist), then higher version; memory-newer rows are reported (are NEWER than LMDB's copy, left in memory) and left, so the next write mirrors memory's version over LMDB's. Both versions are logged for the first five of each kind (vectorapi asked for it on every decision: with it, their direction question would have been answerable from the journal). Production was not hurt: vectorapi's prod boot under 2.21.4 reloaded 3 justice-pa:facts rows (28.9 s audit, 221,955 rows, 1 vCPU), and the 2.21.2 container of the cold copy proved all three memory-older (a patch kept version 3 and lost last_retrieved_at). Test: test_stale_memory adds m0 (version 2 in memory and the snapshot, its LMDB copy replaced offline with an older row's body via lmdb_row_tool): left and reported; reverting the direction check fails 4 checks. Process lesson: my own staging run on real data was the only thing between 2.21.4's audit and a data loss on any store with old divergence; the synthetic e2e could only produce one direction. The local container was never upgraded to 2.21.4 for this reason.Failed to create snapshot: evicted document '_collection_meta/novitax:kb_fact_reviewers' could not be read for the snapshot every ~2 min, 16,586 times since 2026-11-05, WAL 90 -> 276 MB (the October unbootable box had 139 MB; that boot died on memory with no swap, not on the WAL as such). (1) Cause: eviction excluded only pinned collections, so cold _collection_meta rows (tiny, ancient: ideal LRU victims) were evicted; system collections are never mirrored to LMDB, so the snapshot's load callback (database_service.cpp, the evicted-row reader) could read them only from the WAL from the stub's sequence; once one snapshot truncated that WAL file, every later snapshot failed closed (the 2.21.0 rule). Permanent for the process: a write to the row reloads it first, the reload fails, the write fails closed. Before 2.21.0 the same row was written to the snapshot as ABSENT - the next boot lost that collection's config (indexes, uniques, versioning, precision). Now isSystemCollectionName skips _ collections at both eviction selection sites (getEvictionCandidates, selectDocumentsForEviction). (2) The restart replayed 193,776 of 354,089 entries above the snapshot (vectorapi decoded the WAL headers of their cold copy: contiguous files, no torn tail at a file boundary; Persistence manager started, WAL sequence: 1444728; replayed ~ the middle file alone). Cause NOT yet established. Sequences are consumed only by a written entry (++sequence_ in append); replayFile silently skipped an entry failing deserialize (checksum or JSON parse) and silently ended a file at a zero or short length; open() scans all files for the max sequence and ignores failures the same way, so a correct final sequence proves nothing about the middle. Replay now records per file (WriteAheadLog::lastReplayStats, mutex-guarded: replay() also runs at runtime from several threads) applied / at-or-below the snapshot / unreadable (checksum count, first byte offset) / out of sequence order / first-last sequence / bytes read vs file size, logged by PersistenceManager::recover (WARN when anything is off). Consequence, found by asking what an under-replay does rather than assuming it is cache warmth: LMDB had every write (mirrored at write time), so LMDB-served reads were right, but MemoryStore kept the snapshot's version of every row written in the gap, and MemoryStore is the BASE of patch/increment (old fields + the patch, mirrored over LMDB's newer row: silent revert), of updateIfVersion's check, of history and of the next snapshot (which made the old version permanent). Deletes in the gap showed up as 604 memory_only rows in the key audit; updates are invisible to it (ids only). Now boot step "memory/disk version audit" (DatabaseService::repairStaleResidentRows, after the mirror-pending replay, before the key audit, only while the mirror is healthy with zero drift): every resident row of a mirrored collection whose version or updatedAt differs from LMDB's is reloaded (unloadDocument + adoptFromDocStore(quiet) under HistorySuppression: no history, WAL or event). LMDB is authoritative by then because the re-mirror pass and the pending replay have already pushed every memory-authoritative row to it. Cost: one LMDB read per resident row at every boot. (3) listSnapshots() deleted every snapshot-*.tmp and GetStats and the retention pass call it, so a listing during a write killed that snapshot (Failed to reopen snapshot tmp for fsync; vectorapi saw it right after the rescuing boot, and they poll stats). Orphans are now removed by SnapshotManager::removeOrphanedTmpFiles() once in recover, before the snapshot thread exists (a failed write removes its own .tmp). This is very likely also the 2.21.1 "verification failed after write" / "Failed to reopen snapshot tmp" pair I attributed to two concurrent snapshots. (4) Replay never extended systemd's start timeout (initialize() had 10 min from one EXTEND); a longer replay was SIGKILLed and restarted from scratch, forever. Now every 20,000 entries (+ STATUS, + WAL replay: N entries applied) and before the re-mirror pass. Tests: test_snapshot_keeps_evicted seeds three collection configs first (2.21.3 fails 3 checks: snapshots fail; the configs must survive the restart); tests/load_test/test_stale_memory.{cpp,sh} (port 9042: version 1 in the snapshot, a patch to version 2 then SIGKILL, the WAL removed, boot: the audit reloads 10 rows, a patch keeps the newer fields at version 3); test_snapshot_durability (listing leaves a .tmp, recovery's cleanup removes it; 5 snapshots while a thread lists in a loop). Each reverted alone: eviction skip 3 e2e; version audit 12 (all 10 patched rows reverted to state: old); tmp cleanup 1 unit, and the concurrency test alone reproduces the production message (2 of 5 snapshots). The replay timeout and the per-file stats are not pinned by a failing test (checked by hand: 44,985 entries after a SIGKILL, progress lines at 20k and 40k). Process lesson (from the consumer): a failure that retries every two minutes is a silent failure - 16,586 ERROR lines and ~3,400 tenant timeouts a day went unread for two weeks; a stalled snapshot deserves a surface a consumer polls (ROADMAP).similaritySearch per collection on production (2.21.2, 1973 MB host, 4 GB swap): 1.4-5.1 s cold, then 0.18-0.36 s warm, one call past their 5 s client deadline. They suspected a copy we allocate; there is none - scan_vectors scores in place in LMDB's mmap, and the cold cost was the file read from disk (205 MB at ~100-150 MB/s). Their container never reproduced it because copying the data directory left data.mdb 100% in the host page cache. Their prod counters settled the rest: RssAnon 403 MB + VmSwap 889 MB vs a fresh boot's 1245 MB anonymous and 0 swap - the LMDB map (RssFile 1006 MB) was occupying the RAM, and the anonymous memory going out was MemoryStore's own copy of the same 616 MiB of vectors, used while the mirror is healthy only by the degraded search and as a snapshot source. (Their "1.1 GB of growth" was VmRSS + VmSwap, which counts the mmap; VmSwap rising with no pswpout is swap-cache pages dropped without a new write.) Now: MemoryStore::releaseMirroredVectors() runs on every eviction tick, whatever the pressure: for each vector collection while canReleaseVector (mirror healthy, zero drift), in batches of 256 under the collection lock, it compares memory's vector with LMDB's BYTE FOR BYTE and only then drops it (CollectionData::releasedVectors); a vector LMDB lacks or disagrees with goes into vectorsKeptResident (WARN, not retried until a write; eviction also leaves it resident) - releasing it would lose it; skips ids with a write in flight; malloc_trim after >= 16 MB, which only matters for a glibc-malloc build: the packaged server links jemalloc, and the memory goes back only through its background purge (MALLOC_CONF=background_thread:true,dirty_decay_ms:1000,..., set by the systemd unit and the container images) - measured on a 194 MB-vector store: 367 -> 121 MB RssAnon with it, 371 -> 339 MB and flat without it (vectorapi saw the same: 142 of 616 MB returned in a container run without the unit's environment). restoreReleasedVector runs from reloadIfEvicted (every write path, after its InFlightWriteGuard, so the sweep cannot re-release mid-write), reads LMDB OUTSIDE the lock and stores the vector only if still released; a read error fails the write. residentVector falls back to LMDB for a released id - load-bearing: the Update handler logs VEC_DELETE when it answers nullopt, so a release between the write and that call would have written a delete into the WAL. hasVector/getVectorIds/copyVectors include released ids (snapshot reads them from LMDB); evictDocument of a released row marks vectorEvicted; the degraded similaritySearch scores released vectors read from LMDB (a read error is an error, never a shorter answer) - so it loses no candidates. Memory line: of which vectors V MB (R more in LMDB only). Boot still loads every vector from the snapshot (peak unchanged); the first tick releases them. served_from_memory (capability of the same name): FindResponse 9 / SimilaritySearchResponse 3, set to !used_lmdb by every 2.21.3 server; client Client::SearchPath filled by OVERLOADS similaritySearch(..., filters, SearchPath&) and findWithMetrics(..., SearchPath&) - not a member of FindResult/SimilarityResult, which are returned by value (vectorapi asked exactly this; the 2.7.1 SIGSEGV). Before it a degraded vector search had NO signal at all (I first told vectorapi memoryMatchCount would show it: that field is only on FindResponse, and 0 there does not mean LMDB - a degraded find matching nothing also reads 0). Tests: test_dual_write_mirror +1 function (test_mirrored_vectors_released: release count and vector share, a vector LMDB lacks or disagrees with stays, residentVector/hasVector/copyVectors exact, patch restores and keeps, update replaces/removes, delete, degraded search finds and ranks every released vector, nothing released unhealthy or with drift, eviction of a released row then reload, snapshot round trip incl. memory's copy of the disagreeing vector); test_filtered_similarity +5 (served_from_memory false for search, filtered search, findWithMetrics; true for a _ system collection; capability); test_snapshot_keeps_evicted boot 2 now expects Released 300 vector(s) (4 MB) and 0 MB (300 more in LMDB only); test_server_info lists the capability. Each part reverted alone: restore-before-write 2 unit, residentVector fallback 1, degraded LMDB scoring 2, byte compare 2, eviction's kept-resident guard 1. The handler flag was not reverted (the system-collection check is what would fail).disk_only: adopt step: they priced 1,970 vector rows at ~31 MiB, the estimate rose 18 MB, and the reason was that those vectors were ALREADY resident. Mechanism: (1) MemoryStore::loadVector (snapshot load, WAL replay) never touched estimatedMemoryBytes_, while storeVector (writes, adopt) did; (2) evictDocument erased the body and left coll.vectors alone, so a vector outlived its body for the life of the process; (3) serializeStore wrote each collection's vector section from coll.vectors independently of the documents, so the orphaned vector went into every snapshot and was reloaded (uncounted) at every boot - including the vectors of rows whose bodies the pre-2.21.0 snapshot writer had dropped (which is why adopting them added nothing). Production: 237 MB estimated (46%, pressure=normal) with ~39,000 vectors of dimension 4096 (~615 MiB) resident beside it on a 2 GB host; eviction, the one mechanism that frees memory under pressure, could not touch them. The 2.13.0 entry here claimed eviction dropped vectors; it did not (corrected). Now: loadVector counts the delta (and skips a zero-length entry); vectorMemoryBytes_ tracks the vector share beside the estimate (addVectorBytes/subVectorBytes feed both; Stats::vectorMemoryBytes; the memory line reads ..., of which vectors V MB, ..., first logged one tick after start); evictDocument releases the vector under the collection lock when canReleaseVector (mirror wired for the project, healthy, zero drift - LMDB then holds the current copy) and marks EvictedDocumentStub::vectorEvicted; loadEvictedDocument reads it back with readStoredVector BEFORE taking the collection lock and stores it only if it is the call that inserts the document, and a read ERROR fails the reload (so a write refuses rather than proceed, and its undo copy cannot lose the vector); a vector LMDB lacks is WARNed and the body reloads without one. The snapshot's vector section is getVectorIds (resident + released) and copyVectors a batch at a time under the collection lock (memory, else LMDB for a released vector - a read error abandons the snapshot so the WAL is kept, as for bodies - else a second memory look for one reloaded meanwhile), and a vector deleted between the listing and the copy is written as a zero-length entry the loader skips (a pre-2.21.2 loader stores an empty vector that scores nothing). Eviction candidates are sized body + vector. Also fixed: the snapshot iterated the live vector map with NO lock, and so did five gRPC handlers logging VEC_PUT/VEC_DELETE (residentVector/hasVector copy under the lock; hasVector also counts a released vector, so a delete of an evicted row still logs VEC_DELETE); the Update/Upsert handlers now test collection existence with collectionExists (getCollectionInfo walks every document). Not changed: the degraded in-memory similaritySearch (mirror unhealthy) already returned only RESIDENT documents, so a released vector changes nothing there. ⚠ Observable: at the first boot the estimate rises by every resident vector, so a vector-heavy instance whose max_memory_mb was sized from the old figure can boot into hard/emergency pressure (emergency refuses writes until eviction releases enough); raise the budget before upgrading or accept the drain. Tests: test_dual_write_mirror +1 function, 21 checks (counting on insert and on loadVector, once per vector, the placeholder; eviction releases and the share falls; hasVector; copyVectors byte-exact over resident + released; a reload restores the vector exactly and a patch keeps it in memory and on disk; a delete of an evicted row leaves no vector anywhere; an unhealthy mirror keeps it resident; a real SnapshotManager round trip restores every vector and counts them) - the target now compiles snapshot.cpp and links LZ4; tests/load_test/test_snapshot_keeps_evicted gained a 300-row dimension-4096 collection inserted first, a 16 MB seed budget and eviction_max_episode_percent: 100 (with the 1 MB budget the first episode started with 3 documents, so the cap allowed 3 evictions and paused; the test had been evicting 3 rows, now 893), and checks the vector share falls under 4 MB after the seed and is exactly 4 MB after the restart. Each part reverted alone: release 2 unit checks, reload 2, loadVector counting 3, health gate 1, snapshot section 2 unit + 1 e2e (search still passes - it is LMDB-served - which is why the e2e reads the memory line). Deployed to smartbotic-vectorapi's production the same day (budget raised to 1536 MB first: the estimate went to 889 MiB, vectors 616 MiB, 57%; disk_only: 0, so the 7,217 rows adopted on 10-23 reached the snapshots). Their devstack test through their HTTP API (492 dim-4096 rows, 8 MB budget, eviction the only variable): all 492 evicted, vectors 0 MB resident, rankings identical to 6 decimals before and after, ~16,622 bytes freed per row; at emergency pressure their startup createCollection bootstraps were refused (correct, but a reason not to boot into emergency).max_versions was never enforced on growth. Found by smartbotic-vectorapi: 1.4 GB + 458 MB of history on two production collections with versioning OFF since 10-15 (24.7 / 8.5 MiB then), both files last written at the same nanosecond, 2026-10-20 18:06:10.93 - the instant a boot finished "Replayed 14998 WAL entries" (their journal). That boot followed a stop SIGKILLed after 10 min while the pre-2.20.1 writer was snapshotting a 685 MB store, which is what left 14,998 entries to replay. Mechanism: applyWalEntry applies UPDATE/UPSERT through loadDocumentWithHistory and DELETE through remove, both saveToHistory; that version had already been appended at write time (history is written under the collection lock before the WAL entry), so each replaying boot duplicated it. And DatabaseService::initialize runs persistence_->recover before config_manager_->loadFromStore, so during replay configFor() returns the default versioningEnabled = true. Now MemoryStore::HistorySuppression (an RAII counter checked first in saveToHistory) is held across wal_->replay in recover. Second defect: maxVersions pruned only when LOWERED (createCollection/alterCollection), so configure --max-versions 1 on a collection already at 1 reported "cap raised: nothing pruned" and no supported call could reclaim the file; a comment in memory_store.cpp said the snapshot loop pruned - no such call existed. Now PersistenceManager::createSnapshot calls MemoryStore::enforceVersionCaps() after a successful snapshot, which calls HistoryStore::pruneIfGrown(collection, maxVersions) for each capped collection: prune when the file is >= 16 MB (kPruneMinBytes) and > 2x its size after this process's last prune (the first call per process prunes any file over 16 MB, which is the reclaim). Also: boot-time adoption is quiet (adoptFromDocStore(..., quiet); the per-row "write to ... loaded it" line read as a write at boot, and would be 7,219 lines on that instance), the summary counts "not adoptable (their collection exists only on disk)", and the guide says the knobs are instance-wide and the report file is overwritten every boot (both from smartbotic). Found while making the 2.21.0 e2e reliable (it failed 1 run in ~7): (a) evictDocument erased the document under the collection lock and added its stub only after releasing it, so a document was briefly in NEITHER map - a snapshot that had listed it as resident then found no document and no stub and wrote it as deleted (and getMemoryStats undercounted, which is what the test saw); the stub now goes in first, under the collection lock (order collection -> eviction, as in adoptFromDocStore). (b) PersistenceManager::createSnapshot was not serialized: the shutdown's forceSnapshot could run beside the periodic thread's, and within one second both wrote snapshot-YYYYMMDD-HHMMSS.dat and its .tmp (logged: "verification failed after write", "Failed to reopen snapshot tmp"); createSnapshotMutex_ now serializes it. Honest limit: neither race is pinned by a test - with the mutex removed the loop passed 10/10; the evidence is the logged failure and the code. The e2e's memory check is now taken after a restart with a budget that evicts nothing (a sample under live eviction races the stats themselves), plus "no snapshot failed". Also from vectorapi (prod's first 2.21.0 boot, report mode: 7,217 disk-only, 784 ms): report mode said only "reported" and could not price adopt; it now says "adopt would load them" / "not adoptable: the collection exists only on disk", and the JSON has collection_in_memory. Tests: test_history_audit_scan +8 (pruneIfGrown: threshold, prune to 2 per document 21 MB -> 1 MB, not again until doubled, again after), tests/load_test/test_replay_history.{cpp,sh} (port 9039: 3 patches on a versioned and a versioning-off collection, SIGKILL, a boot that replays; SERVER_BIN): the released 2.21.0 shows 6 versions instead of 3 and 3 instead of 0; this build 3 and 0.storage.consistency repair knobs. The owner: "first is to prevent these issues, repair must be automatic with config knobs"; defaults chosen by the owner: disk_only: adopt, memory_only: report. (1) The cause of the production disk-only rows (7,219 on one instance's first 2.20.2 boot, 0 the other way, the store loaded from one snapshot with no WAL replayed and nothing evicted - smartbotic-vectorapi's control): serializeStore read each evicted document back through the load callback, which scanned ONLY the WAL from the stub's sequence (PersistenceManager::loadDocument). The WAL rotates at 100 MB (maxWalSizeMb, not configurable) and truncateBefore(walSeq) deletes rotated files a snapshot covers, so a document still evicted at the NEXT snapshot was unreadable and written as a zero-length entry with a WARN ("will be missing from the snapshot"); the next boot lacked it while LMDB had it. The production journal held 69 of those "could not be loaded from WAL" WARNs (its trailing "Likely a pre-v1.7.3 snapshot already lost them" sent readers to the wrong cause). Consequence beyond the ghost writes: a backup of snapshots/ + wal/ was not a backup, and Recovery complete: N docs counts memory so it looked fine. Now the load callback reads LMDB first (it holds every write to an evicted row, since a write reloads it) while the mirror is healthy with zero drift, the WAL for system collections or a degraded mirror; the evicted loop goes through copyDocuments (which also copies an id reloaded since it was listed, previously written as absent); and copyDocuments THROWS for a still-stubbed document it cannot read, abandoning the snapshot so the WAL is kept. The throw alone would be a regression (every snapshot fails, the WAL grows, the 2.20.1 outage): reverted LMDB read -> 22 refused snapshots, 600/600 rows survive; they ship together. (2) Failed LMDB copies are remembered: a mirror failure only flips health for the process; the next boot re-mirrored only what WAL replay touched, so a snapshot in between made the divergence permanent (memory-only for a failed put, disk-only for a failed delete). storage/mirror_pending.hpp (header-only, <data>/mirror-pending.log, one JSON pair per line, fdatasync'd, torn last line skipped) is fed by MemoryStore::setMirrorFailureSink (drift went up during mirrorWriteToDocStore/mirrorVectorToDocStore; false positives harmless), the boot re-mirror pass's failures, backfill and replication apply. Boot step "mirror-pending replay" (before the audit) runs MemoryStore::syncDocStoreFromMemory: present in memory -> put_with_vector (vector from memory, else removed if the marker says none, else kept), absent -> del + del_vector; failures stay in the file. Memory is authoritative for those rows by construction. (3) storage.consistency (Config::consistencyDiskOnly/consistencyMemoryOnly, unknown value -> report with an ERROR): disk_only adopt (adoptFromDocStore, now public; skipped for a collection not in memory) / report / remove (del + del_vector); memory_only report / write (syncDocStoreFromMemory) / remove (MemoryStore::remove, actor system:consistency-repair, so WAL, history and a DELETE event). Complete lists in <data>/consistency-report.json every boot (the log keeps 10 ids per collection; a consumer could not act on a truncated list). Audit lines are WARN (were ERROR - 41 ERROR lines at boot read as a catastrophe), the summary ERROR only when a repair failed. Why memory_only is not automatic (smartbotic-vectorapi): a memory-only row is a lost put (repair: write) or a lost delete (repair: remove) and nothing in it says which; for an API key the second is a revoked credential. Before 2.20.2 these rows' writes were genuinely broken: on the running process a write to an evicted row whose WAL copy was gone threw (2.12.1 fail-closed), after a restart it answered not-found and an insert overwrote; a key revocation in that state did not revoke. Also corrected: the 2.20.1 code comments said "2.21.0" (it was planned as a feature, then released as a patch). Tests: test_snapshot_durability +1 (an unreadable evicted document fails the snapshot, no file left), test_dual_write_mirror +3 (the pending log incl. a torn line and control characters, the sink gets the qualified name for a failed put and delete, sync from memory with a vector and a disk-only delete), tests/load_test/test_snapshot_keeps_evicted.{cpp,sh} (port 9038: 600 x 200 KB rows, 1 MB budget, snapshots every 2 s, so the WAL rotates; restart must hold all 600; SERVER_BIN runs it against another binary - the released 2.20.2 loses 3 rows), test_disk_only_rows boots 4-6 (pending replay writes one row and deletes another, disk_only=remove, memory_only=write, the report file, boot-time adopt, memory_only=remove frees the id). Reverted: pending replay 5 e2e checks.catalog_hardware row: reads found it, PATCH/PUT/DELETE answered 404). Reads are served from LMDB; writes (and insert's duplicate check) look only in MemoryStore, and since 2.12.1 only reload an EVICTED document (a stub in evictedDocs_). A row in LMDB with no resident copy and no stub was therefore invisible to every write: patch/update/delete not-found, and insert or upsert of the id ACCEPTED, overwriting it at version 1 (the mirror's mdb_put has no NOOVERWRITE). MemoryStore is rebuilt from snapshot + WAL and never from LMDB, so no restart repairs it. How the two came to disagree is NOT established (ROADMAP 5f: most likely the pre-2.20.1 snapshot writer's gap between listing resident documents and evicted ids). Now MemoryStore::adoptFromDocStore, called from reloadIfEvicted when there is no stub (so from every write path, after its InFlightWriteGuard): resident -> nothing; else one LMDB exists() (a miss is every insert of a new id), and on a hit the row is read UNDER the collection's unique lock - every write mirrors to LMDB under that lock, so the body read is current - and emplaced with its expiry index entry and its vector; WARN per row. Gated on mirror healthy AND zero drift, the gate LMDB-served reads use: otherwise MemoryStore may be AHEAD of LMDB (a delete that never reached LMDB) and adopting would resurrect it. Skips _ collections, and an id held under the other legacy alias of a default-project collection (bare x and default:x share one sub-db; making a second copy would be the alias problem, not this one). An exists() that throws logs WARN and proceeds as before 2.20.2; a get() that throws after a hit propagates (fail closed, as reloadIfEvicted does). Also fixed: the Upsert handler decided inserted (and whether to run preserveUnchangedEncryption, and to stamp createdBy) from store_.exists() BEFORE the store's upsert, so a non-resident row - evicted (since 2.12.1) or disk-only - was reported as newly inserted; it now calls MemoryStore::ensureResident first. _created_by of an EVICTED row was never overwritten (I first told a consumer it was - wrong): MemoryStore::upsert's update branch reloads the row and copies createdBy from it. A DISK-ONLY row's was, because the upsert took the insert branch and re-created it at version 1 with a new createdAt; that is the only pre-2.20.2 mis-attribution, and only where the boot audit finds or found such rows. Boot step "memory/disk key audit" (DatabaseService::auditMemoryDiskKeys): per LMDB sub-db, the ids LmdbDocumentStore::list_ids returns (keys only, values never touched) against MemoryStore's resident + evicted ids over both aliases, merge-compared sorted; ERROR per collection with counts and 10 sample ids for "on disk but not in memory" and "in memory but not on disk", one summary line with the time taken. Read-only. Measured (100,000 rows in two 50,000-row collections, release build): 118-140 ms; peak RSS (VmHWM) 271-275 MB with it against 269 MB with the call removed, so a few MB, proportional to the LARGEST collection's id count (two sorted id vectors at a time), not the store; the key walk reads LMDB leaf pages, which are page cache, not anonymous memory. The reverse direction has no fix: those rows are writable and invisible to LMDB-served reads. A disk-only row that is written becomes an ordinary document (WAL, then the next snapshot), so if it was a delete that never reached LMDB (candidate 3) the write keeps it. No format, marker or migration: 2.20.1 runs on the same data directory. Tests: test_dual_write_mirror +1 function (rows planted in LMDB only: patch merges into the on-disk body, update, updateIfVersion at the on-disk version, upsert keeps version and createdAt, insert refused DuplicateDocumentId with the row untouched, remove deletes on disk, a truly absent id still not-found, unhealthy/drift adopt nothing, the bare-alias case, a vector row brings its vector), tests/load_test/test_disk_only_rows.{cpp,sh} (port 9037; rows planted with the server stopped by lmdb_row_tool.cpp, which also deletes one on disk only; the audit names all of them, a real client drives every write, inserted=false, a third boot shows the written rows are no longer disk-only and the unwritten reverse row still reported). Reverted: adoption 12 unit + 13 e2e (incl. the production clobber: the insert overwrote the ghost row), the health/drift gate 2, the handler's ensureResident 1.oom-kill, 24 restarts a day, journal only status=9/KILL), so the WAL was never truncated (139 MB), and on 2026-10-19 recovery itself no longer fit - a continuous crash loop that died in init, before READY (they confirmed it: 0 READY lines in 120 cycles, and no reseal: the data dir's own mtime proved encryption-reseal.pending was never there). Restored by adding swap; they copied the WAL (the only record of ~69 h of writes) first. The writer's peak was the working set plus ~3 copies: getAllDocuments copied each collection, serializeStore returned the whole body as one buffer, the LZ4 pass built a second, and verifySnapshot read the file back whole. Now BodyWriter (snapshot.cpp) stages one chunk (Config::chunkBytes, 16 MB), compresses it and writes it, CRC by crc32::extend; the header is a placeholder rewritten with seekp(0) at the end; documents are copied 256 at a time (MemoryStore::getDocumentIds + copyDocuments, which falls back to the evicted copy so a document evicted meanwhile is not dropped - the WAL holding it is truncated after the snapshot); verify streams in 1 MB blocks; load frees the compressed body before deserializing. Format unchanged (v4). One subtlety: the per-collection doc count precedes the documents and cannot be back-patched once its chunk is on disk, so it counts every listed id and a document deleted before it is copied is written as a ZERO-LENGTH entry, which every reader since v1.8 skips (the empty body's parse error is caught). Visibility: snapshots/snapshot.in-progress (start time, WAL seq) exists while a snapshot runs and is removed when it returns or throws, so only a killed process leaves it; recovery logs ERROR "The previous snapshot did NOT complete" on every boot until one completes, an INFO "Recovery input: WAL N MB, newest snapshot X, M min old", and a WARN when the WAL is >= 2x max_wal_size_mb (also before each snapshot attempt); boot logs Boot: <step> for each step after the backfill (the production loop died in a silent 3 s there). Not fixed, ROADMAP 5e: boot still needs the whole dataset in MemoryStore. Test: test_snapshot_durability +3 (a 154 MB single-collection store: the snapshot's peak RSS grows 51 MB; multi-chunk round trips compressed and raw; the marker). Reverted (whole-body buffer + whole-collection copy): peak grows 585 MB, the bound check fails. Measured in production by smartbotic-vectorapi: before the upgrade 34 of 43 client Deadline Exceeded fell within -15 s/+120 s of a snapshot completion (3.7% of elapsed time; 200 random reshuffles: mean 1.4, max 7), i.e. the old writer's paging stalled clients hourly, not only risked an OOM; after it the server's VmSwap went 827 MB -> 87 MB and stayed there across a snapshot (VmRSS 1178 MB, unmoved by the snapshot). The stall count after the upgrade needs several clean snapshots to mean anything (about even odds per snapshot before).std::regex. Reported by smartbotic-vectorapi from a consumer's measurements through their ?filter= pass-through; all four checked against filter_eval.hpp first. (1) ⚠ Availability: the arm built a std::regex from the caller's pattern for EVERY row and ran regex_search inside the scan's read txn; std::regex backtracks, so (a+)+$ over a long failing value grows exponentially (vectorapi, engine in isolation: 26 bytes 11 s, x4 per byte), reachable by any key holder with a read grant who can also plant the row. Measured end to end here with the engine reverted: a 5,001-byte value took the find past its 20 s deadline and the server thread kept running after the client gave up. The 2.16.0 schema pattern had already chosen RE2 for exactly this reason (json_schema.hpp) and the filter path was never moved. (2) catch (regex_error) { return false; } made an invalid pattern indistinguishable from "no match"; (3) (?i) was one of those (not ECMAScript); (4) classes matched BYTES: sz[áÁ]mfejt never matched, [öÖ] matched any text sharing lead byte 0xC3. Now storage/regex_filter.hpp: RE2 (UTF-8, max_mem 1 MB), compiled once per thread per pattern (bounded cache of 64; failures cached too), PartialMatch = search semantics. DatabaseGrpcImpl::refuseInvalidPatterns refuses on Find/Count/SimilaritySearch (caller filters only, before the view merge) and CreateView: INVALID_ARGUMENT, reason invalid_pattern, fields. A view where or policy row predicate STORED before this with a pattern RE2 cannot compile is not refused at read time (it would break every read of the view); it fails closed, as an invalid pattern always did. Observable: backreferences and lookaround are now invalid_pattern - the one direction that breaks a working query. Capability re2_regex_filters. tests/CMakeLists.txt links RE2 into every test target (filter_eval.hpp is included by memory_store.cpp, document_store_lmdb.cpp, relation_cascade.cpp). Test: tests/load_test/test_regex_filters.{cpp,sh} (port 9036, 39: refusals on every entry incl. lookahead/backreference/view, (?i) incl. non-ASCII folding, UTF-8 classes and ., anchors, non-string values, count/similarity/view use the same engine, (a+)+$ on 5,001 bytes and ^(a|b)*c$ on 200,000 bytes each under 2 s, server still up). Reverted alone: handler refusal 7 fail; engine (std::regex per row) 8 fail, then the client aborts on Deadline Exceeded at the backtracking query._expires_at. Reported by smartbotic-vectorapi after a consumer's incident: TTL could be written (insert/upsert ttlSeconds, patchWithTtl, defaultTtlSeconds) and never read back, so (1) a backup checked against live showed a row "missing" that was an expired 48 h idempotency marker - expiry is lazy, a copy taken while the server is stopped keeps expired rows until the next server sweeps them - and (2) a restore could not carry the expiry, making an expired row PERMANENT, which for an idempotency marker suppresses the work it guards forever. The server had always sent it (Document.expires_at, absolute ms since epoch, toProto); the client's documentToJson dropped it. Now get/find/export attach _expires_at when non-zero (absent = no expiry; it may lie in the past - the sweep runs every second, and a restrict relation can hold a row past its TTL). Filterable (capability document_expires_at): both resolvers (filter_eval::resolveFilterValue, the LMDB yyjson resolver) map it to the stored expiresAt, with 0 resolving to ABSENT - otherwise _expires_at < X would match every document that never expires. Not a sort key. Reserved in write bodies (isReservedField), and the client strips it too (writeBodyText, update()'s cleanData) because consumers run older servers that would store it as a field - the 2.13.0 shadow-field defect. Restore guidance in the guide: absent -> no TTL; past -> skip; else ttlSeconds = ceil((_expires_at - now)/1000). Tests: tests/load_test/test_document_expiry.{cpp,sh} (port 9035, 18: get/find/export carry it only where set, filters exists/lt/gt/count, patchWithTtl moves it, a read body re-inserted or updated does not store it, a 1 s row is reaped). Reverted alone: read 4 fail, filter resolvers 4, write strip (both sides) 2.smartbotic-db-cli configure. Asked by smartbotic-vectorapi before a production history prune: the CLI - the only admin tool on a server host - could neither switch versioning off nor set maxVersions, so the measured answers had no route to an operator, and they declined to hand-roll a tool against a live store. configure <collection> [--versioning on|off] [--max-versions N]: versioning through configureCollection with timestampPrecision = "" (the struct's default "ms" would otherwise RESET precision - caught by the test), the cap through createCollection(existing, <current defaultTtlSeconds>, false, N, 0) so the prune cannot clear the TTL (0 is a real value), --max-versions 0 refused (it means unlimited, which is how the consumer's 195 MiB history file grew), elapsed time printed; the history file's size is NOT visible over the API, so the command says to compare the .hlog rather than inventing a number. info now always prints default_ttl_seconds and marks max_versions 0 as unlimited. Test: test_collection_admin drives the real CLI between two client phases (seed 10 versions + TTL 3600; after configure --versioning off --max-versions 2: history <= 2, TTL 3600, cap 2, versioning off, precision still ns, a later update records nothing). Reverted (TTL passed as 0, precision left at the default): 3 checks fail.validFrom:lte:X admitted rows whose validFrom was an explicit null, and year:gte:2025 admitted the STRING "1900". Not designed: filter_eval::compareJson used nlohmann's operators, which order ACROSS types (null < boolean < number < string). Decided with the owner (released, not just documented): GT/GTE/LT/LTE now hold only when both sides are numbers or both strings (comparableForRange); a null, boolean, object/array or mismatched value never satisfies a range, and a null/boolean bound matches nothing. EQ/NE (JSON equality), EXISTS (an explicit null exists), absent-field handling and SORT ORDER are unchanged. The index had to change too: lookupIndexRangeTxn now declines a bound that is not a number or string, because rangeOrderedFromIndex (range + sort on one field) trusts postings WITHOUT re-judging - a single-type index of only true (true and false carry different tags) or only nulls would otherwise have served rows the scan rejects; my first test missed it because its boolean index held both true and false, so it counted as mixed and was declined, and reverting the gate failed nothing until the test used single-type indexes. Capability typed_range_filters (the meaning of an existing operator changed, so it gets a name). Every filter path funnels through compareJson (scan, MemoryStore, views, row predicates, filtered similarity). Tests: tests/load_test/test_typed_ranges.{cpp,sh} (port 9034, 30 checks, every case on a scanned AND an indexed collection, plus count, range+sort, sort order unchanged). Reverted alone: comparison rule 17 fail, index gate 2. Still open (ROADMAP 6): sort and filter disagree about an ABSENT field. ABI: one constexpr added, soname 2.HistoryStore::fileMutex), not one global mutex: a prune or rewrite of one collection no longer stalls history-recording writes in every other. (2) The maxVersions prune streams in two passes (count per doc, then copy the newest N; a no-op leaves the file untouched) and runs AFTER createCollection/alterCollection release MemoryStore's global and collection locks - 2.17.1 ran it under the global lock exclusively. (3) Targeted reseal: an online encryption upgrade requests a reseal only when it actually rewrote plaintext, naming its project; the reseal compacts only the named projects (*, a failure path, or a pre-2.17.2 marker containing 1 means all). Found live: a flag switched on over values already ciphertext (through a bare alias) cost a 3.5-minute restart compacting a 262 MB env nobody had touched. (4) _vector is never encrypted (isEncryptedPath): since 2.17.0 the whole-document rule encrypted the embedding before the store extracted it, so EVERY insert carrying a vector into an encrypted collection was refused (type must be number, but is string); vectors stored before the flag was switched on kept searching, which is why a consumer's populated-collection flip test passed. (5) UX: the CLI verdict reads CLEAN (UNSEALED: ...) while a reseal is pending (a consumer saw CLEAN with plaintext still in the WAL and data.mdb); a missing storage.encryption.key_file names the setting instead of "data will be lost on restart". Tests: test_history_audit_scan (per-file lock: a rewrite of one collection does not block an append to another, with the same-collection control; prune keeps the newest N), test_encryption_at_rest (no reseal over already-encrypted values; the reseal compacts 1 of 2 projects and the first seal both; an encrypted vector collection inserts, searches at 1.0, returns the numeric vector; a flipped vector collection takes new vectors). Each reverted alone: per-file lock 1, rewrote-something condition 1, targeted compaction 1, vector exemption 4.encryption-verify stalled writes server-wide. It audited history through HistoryStore::rewrite, which holds the GLOBAL append lock for each file it reads: every history-recording write (update/patch/upsert of an existing id, delete) in EVERY collection waited while a large file was read - minutes for a 230 MB file, seen by a consumer as Deadline Exceeded on an unrelated collection (a blocked upsert holds its collection lock, so that collection's reads stalled too; a collection with versioning off never waited, which is how the consumer's own heartbeat evidence refined the model). Now HistoryStore::forEach, a read-only scan without the lock (a record appended concurrently is either complete, CRC passes, or ends the scan). tests/test_history_audit_scan.cpp starts an append from INSIDE the scan callback: it completes under forEach, and a control asserts it waits under rewrite() - so the harness is shown to detect the lock. (2) The migration's memory peak was a multiple of the largest history file: rewrite collected every record before writing. Now streamed (one record in memory); a no-change pass leaves the file byte-identical with no tmp. Mattered for a consumer's 2 GB production host with a 114 MB history file. (3) Compaction had a window with NO data.mdb: it moved the original aside, then renamed the copy in; a kill between the two left an empty env at the next boot. Now one atomic rename over the original. (4) info reported the collection's OWN encryption options, not the enforced rule (merged with the bare alias, encryptionOptionsFor): a consumer's credential collections read encrypted: no while every value was ciphertext, because their options sat on a bare-name phantom from the pre-2.4.5 client bug. The flag can be wrong in both directions (true with nothing encrypted before 2.17.0); GetCollectionInfo now reports the merged rule, and the CLI prints versioning on/off (a consumer went to file mtimes to learn that history had been switched off). (5) project:_name collections are refused (INVALID_ARGUMENT, reason reserved_collection_name), in gate() (all handlers) and first in Find (before its existence check); DropCollection exempt so leftovers can be removed. Pre-existing since 2.3.0 and found by a consumer probe: the LMDB mirror tests the COLLECTION PART for a leading _ (and skips the write) while the read paths test the WHOLE qualified name (and go to LMDB), so a write answered ok, lived only in memory and the WAL, and no read found it. Bare _name (global, never qualified by the client) is unchanged. Decided with the owner: refuse rather than store. (6) createCollection(existing, lower maxVersions) prunes the history on disk, as the RPC-less alterCollection always did; before, the setting was accepted and nothing was trimmed, so history kept with maxVersions = 0 could never be cut back (a consumer's function registry had a 114 MB file of old script copies). Synchronous inside the call. Tests: test_history_audit_scan (unit), tests/load_test/test_collection_admin.{cpp,sh} (port 9033: every reserved-name refusal incl. find/count/patch, global _ names still work, the drop is let through, 12 versions pruned to the newest 3), test_encryption_at_rest +3 (info on a bare-alias-encrypted collection). Each part reverted alone: reserved-name check 5 fail, info merge 1, prune 1; the lock-free scan is pinned by the unit test's control. Process lesson: two claims of mine in the 2.17.0 consumer notes were wrong in ways the consumers' measurements exposed (that info shows the flag; that the verifier's lock was held for the whole run) - their outside measurements against my reading of the source is what found all six items. ABI: no public type changed, soname 2.encrypted=true collection read encrypted: no?"), confirmed by experiment (a canary written to an encrypted=true collection grepped back out of data.mdb in plaintext). The owner: "a very big mistake, this must be patched in", migration tested on a throwaway instance and a copy of production data first, no double encryption, notify the consumers. Five holes, all silent: (1) CollectionOptions::encrypted was stored, persisted and reported and NO code read it - true since the initial extraction; (2) CollectionOptions::sensitiveFields likewise (declarable in migration files, never used); (3) the built-in patterns *.password etc. became .*\.password, which needs a dot - a TOP-LEVEL password/secret/token/api_key/apiKey/credentials was plaintext; (4) the Patch handler and every migration write op (insert, upsert, update, upsert_setting, generate_secret) never encrypted; (5) strings inside arrays were neither encrypted nor decrypted (decryptJsonField's array branch recursed into containers only). Plus, found on the way: migration-file collection options lived under the BARE name while clients write the qualified one, so they never applied (MemoryStore::encryptionOptionsFor merges x / default:x); and decryptSensitiveFields was gated on doc.encrypted, a marker the set-op / migration paths never set. Rules now (EncryptionRule): an encrypted collection encrypts every non-null value (strings $ENC$, other types $ENCJ$ = ciphertext of the JSON text, restored on read), sensitive_fields paths and everything under them, the patterns at ANY depth ((?:.*\.)?password), array elements included. Never twice: a value already carrying $ENC$/$ENCJ$ is skipped - the idempotency the migration rests on. Comparisons over ciphertext are REFUSED (the owner: "deny indexing and similar features on encrypted values ... refute it if you can" - not refutable: random IVs make a filter never match and a unique constraint never fire): find/count/similarity filters and sorts, SEARCH on an encrypted collection, index/unique/composite/relation declarations, GetIndexValues, increments, set ops on an encrypted collection -> INVALID_ARGUMENT (set ops FAILED_PRECONDITION), reason encrypted_field, fields named. Declared indexes on now-encrypted fields are DISARMED at boot with an ERROR naming them. The migration (DatabaseService::migrateEncryptionAtRest, end of initialize(), before any thread or listener): per canonical collection, rows needing encryption are found by scanning LMDB (auditTree), each rewritten by MemoryStore::rewriteBodyInPlace (transform under the collection lock, SAME version, no history entry, mirrored to LMDB, persisted to the WAL; an LMDB-only row is written directly; aliases tried in turn and NEVER created - the first cut created empty alias collections, found on the production-data copy), history files rewritten (HistoryStore::rewrite, tmp + rename). Then the SEAL: PersistenceManager::sealAfterRewrite rotates the WAL, takes a VERIFIED snapshot, deletes every older snapshot and every archived WAL file (nothing deleted unless the snapshot verified), and ProjectStoreRegistry::compact rewrites each env with mdb_env_copy2(MDB_CP_COMPACT) - required: reverting it leaves 15 canaries in data.mdb, LMDB is copy-on-write and freed pages keep old bytes - closing and reopening the env, after which index/relation arming is re-applied. Marker encryption-at-rest.v1 (runs once); encryption-reseal.pending makes a later boot redo the seal. sd_notify EXTEND_TIMEOUT per collection. Online upgrade: createCollection(existing, encrypted=true / sensitive_fields) now switches encryption ON (never off) - it used to ignore options on an existing collection - encrypts rows and history at once, logs the full options to the WAL (replay upgrades, never downgrades), and requests a reseal at the next boot. Verifier: VerifyEncryption RPC (admin) / Client::verifyEncryption() / smartbotic-db-cli encryption-verify counts ciphertext values, plaintext-where-required, double-encrypted, undecryptable, for rows and history, plus sealed-or-not; exit 1 on any finding. Capability encryption_at_rest. Also fixed in the client: 29 throwing reads (find, count, ...) threw without the server's error-detail trailer, so the reason never reached callers - found because encrypted_field came back empty. And the non-throwing calls, found by smartbotic-vectorapi before the tag: createIndex, createUniqueIndex, createCompositeUniqueIndex, createRelation, setAdd, setRemove turned a refusal into false / success=false and dropped the trailer, so a permanent encrypted_field refusal was indistinguishable from an outage and a consumer mapped it to 503 (retry forever) - the mirror image of the 2.12.0 FAILED_PRECONDITION ambiguity. Now each has a FailureDetail& OVERLOAD (not a CreateIndexResult member: that public struct would change size under soname 2); reverting the recording fails 5 checks. Tests: tests/load_test/test_encryption_at_rest.{cpp,sh} (port 9031) seeds with the RELEASED 2.16.0 server (packaging/old-server.sh 2.16.0 unpacks it from the apt pool - run it before dev.sh e2e all), with a migration file using bare names, then upgrades: 11 canaries proven plaintext on disk before, 44 "nowhere on disk" checks after (LMDB, WAL, snapshots, history), 72 functional checks (exact values and types, history decrypts, the verifier clean and sealed, every refusal, new writes encrypted, the online upgrade, two restarts, the migration ran exactly once). Each part reverted alone: top-level patterns 4 fail, whole-collection rule 5, compaction 15, history rewrite 3, double-encryption guard 4 (a nested password read back as $ENC$...), patch encryption 2, WAL/snapshot seal 3. production-data copy (a nightly backup, 22,298 rows, 626 MB; tests/load_test/migration_copy/, compare.py runs on the HOST - the build image has no python): decrypted dumps of every collection of every project with the released 2.16.0, a 2.16.0 CONTROL after its own TTL sweep, 2.17.0 after the migration, 2.17.0 after a restart - 0 differing bodies in every comparison (16,812 common documents); the only documents not in both are executions/sessions expiring by TTL between dumps (the control proves 2.16.0 drops them too). Migration: 12 rows + 235 history versions encrypted (vectorapi_keys/settings, providers, workflow node configs holding bot tokens), ~6.5 min, smartbotic-automation compacted 626 MB -> 35 MB; encryption-verify CLEAN and sealed, and again after the restart. Two process mistakes on the way, both caught: two copy runs once overlapped on one directory (a stopping server writes a final snapshot into it) and the run was discarded; the first copy pass found the alias probe creating empty collections. What the database cannot fix: copies made BEFORE the upgrade (backups, pre-upgrade-*, nightly backup archives, replicas, disk blocks) keep the plaintext; credentials stored before 2.17.0 should be rotated. ABI: additions only, soname 2.service/src/schema/json_schema.{hpp,cpp}: compiled once into a node tree; type (incl. arrays of types, "integer" accepts 5.0), properties/required/additionalProperties (bool or schema)/min|maxProperties, min|maxLength in CODE POINTS, pattern via RE2 (linear time, no recursion - std::regex can go exponential or overflow the stack on caller strings; RE2 was already a gRPC dependency, now linked directly and in the server's Depends), format date-time/date/email/uuid, numeric bounds, items/min|maxItems/uniqueItems (sorted copy, not pairwise), enum/const, boolean subschemas; annotations accepted and ignored (default NOT applied). Every other keyword is refused at compile time so a schema never looks stricter than what is enforced. Enforcement is a MemoryStore::SchemaCheck callback (MemoryStore stays independent of the schema module, so unit-test targets that compile memory_store.cpp need no RE2), run under the collection lock BEFORE any mutation in insert, update, updateIfVersion, upsert, patch (on the MERGED body, after increments and the size guard - a merge-patch null removing a required field is caught), restoreToVersion (so restoreToDate), setAdd/setRemove; NOT in loadDocument (WAL replay, replication apply). The installed check (DatabaseService) looks up SchemaRegistry (shared_ptr entries, an atomic count makes the no-schema path one relaxed load), validates schemaView(body) = a copy with read metadata and _vector removed and sensitive fields decrypted (EncryptionManager::decryptTree), throws SchemaViolation{paths} in enforce mode or counts + rate-limited WARN in audit. Handlers map it to INVALID_ARGUMENT, reason schema_violation, fields = paths (8 handlers; BatchInsert counts it as an item error). Messages never echo values (a value may be a decrypted secret). Persistence: CollectionCfg::schema/schemaMode in _collection_meta (written only when set, so schema-less records are byte-identical), armed at boot by applySchemaDeclarations() (a stored schema that no longer compiles is logged ERROR and reported armed=false). RPCs SetCollectionSchema (Write-gated, refused read-only / mirror unhealthy; ARMS FIRST under withCollectionWriteLock, THEN scans existing rows through export_scan in one read txn, then persists - so no write lands unchecked between scan and arm; enforce + violations -> previous entry restored, in-band success=false with count and 10 examples), GetCollectionSchema (Read-gated: the schema as set, mode, refusals/audit counters, armed), SuggestCollectionSchema (Read-gated, row predicate and masks applied, SchemaSuggester: type unions, required = present in every row, additionalProperties:false, formats, small enums NEVER for a sensitive path, lengths/ranges only in description; the suggestion accepts every scanned row by construction). Client: setCollectionSchema/removeCollectionSchema (result with reason), getCollectionSchema (nullopt = none; throws), suggestCollectionSchema - all gated by capability collection_schema (the first real use of 2.15.0's requireCapability: an older server gets server_unsupported before anything is sent). CLI schema, schema-set <c> <json|@file> [--audit], schema-drop, schema-suggest. Not done: a migration-file op (the existing-row check lives in the handler; consumers call setCollectionSchema at startup). ⚠ Found on the way, NOT fixed (independent of schemas): the built-in sensitive-field patterns are globs like *.password compiled to .*\.password, so they match only a NESTED field - a TOP-LEVEL password/api_key/token is stored in PLAINTEXT, and the patterns are not configurable. My first sensitive-field test passed vacuously because of it; the e2e now uses creds.password and greps the data directory for ciphertext (grep -F - a plain '$ENC$' regex anchors at end of line and found nothing, a second near-vacuous check). Recorded in ROADMAP 6. Tests: tests/test_json_schema.cpp (89: every keyword both ways, code-point lengths, compile refusals incl. backreferences, the violation cap, the suggester accepting its own rows, never-enum for sensitive paths via the e2e); tests/load_test/test_collection_schema.{cpp,sh} (port 9028, encryption ON, 56 + 5 after a restart: the owner's 128/130 example, every write path refused with the row untouched, restore with a control proving restore otherwise works, enforce/audit over existing rows with the right example ids, invalid schemas, remove, suggest-then-apply over 40 rows, _vector not an unknown key, a 5-character password accepted though its ciphertext is longer); test_server_info old phase: schema calls refused with server_unsupported by an older server. Each part reverted alone: merged-patch check 4 fail; decrypt before validating 1; no-enum for sensitive paths 2; existing-row check 2; boot arming (the armed-at-boot check fails); restore check 2. A revert script that used restore as both a case name and its undo command silently tested nothing for that case - caught because its result looked too good. ABI: additions only (new nested types and methods), soname 2.smartbotic-database declared Depends: libsmartbotic-db-client (= VERSION), because the server linked the shared client library - not for any client code (it includes none) but because the generated protobuf/gRPC objects were compiled into that .so. So on any host running the server, a client upgrade dragged the server along or apt refused. Now the server links smartbotic_db_proto directly (ldd shows no client library), its package depends on the system libraries it actually uses, and build.sh --only client|server publishes one side. (2) No way to ask the server anything: no RPC returned a version or a feature list, so a new client could only send and hope - and a new FIELD on an existing request is silently ignored by an old server (the 2.14.0 filters case), which is wrong data that looks right. New RPCs were always safe (UNIMPLEMENTED). Now: GetServerInfo returns version, commit, the feature-name list (service/src/server_capabilities.hpp, 21 names back to projects) and echoes the sbdb-client-version metadata the client attaches to every call (in attachAuth, which every context passes through - unary, write and stream). Client: serverInfo() (nullopt = pre-2.15.0 server, i.e. none of the 2.15.0+ features; THROWS when the server cannot be asked, because an outage reported as "old server" would make every new feature look unsupported during a blip; cached 60 s per Client, refresh to ask now), serverSupports(name), Client::Capability constants mirroring the server list, and an internal requireCapability() that throws FailedPrecondition, reason server_unsupported, before sending. Names, not version numbers, so a backport or patch says exactly what it has; a name is never reused and a changed meaning gets a new one. similaritySearch with filters now also refuses up front against a 2.15.0+ server that lacks the feature (pre-2.15.0 servers keep the 2.14.0 filters_applied guard). CLI server-info. packaging/compat.sh <released-version> runs this tree's client against a released server (installed from the apt pool in a trixie container) and the released CLI + library against this tree's server - both directions, green against 2.14.0 and 2.13.1. ⚠ It found a released packaging bug on its first run: smartbotic-db-cli links liblmdb (verify-subdbs) and OpenSSL (generate-tls-cert) but its package declared neither, so installed WITHOUT the server package the CLI could not start (liblmdb.so.0: cannot open shared object file) - every release up to 2.14.0; invisible wherever the server package was also installed. Fixed in control.cli. The check helper's first version also passed commands that had failed (it tested a grep -v filter's exit code) - checks now test the command's own exit code. Tests: tests/load_test/test_server_info.{cpp,sh} (port 9027): current 35 (version, commit, all 21 names agree both sides, the header arrives, caching, ordinary calls, filtered search), down 1 (throws, not nullopt); old 9 through compat.sh. Reverted alone: no version header 1 fails; outage reported as old server 1 fails. Also in this release, from 2026-10-09: index-create refuses a flag as a collection or field name (two bogus declarations on a production instance came from index-create "users email" --unique). 2.15.0 is the last lockstep release: a host must take both 2.15.0 packages once (the 2.14.0 server package still pins its client library); after that either side moves alone. ABI: additions only (methods and new types), soname 2.similaritySearch, exact; and vector search finally obeys the access policy. Requested by smartbotic-vectorapi, design agreed before code. They emulated a filtered vector search by widening an unfiltered one (topK x4 per pass) and intersecting with find() ids in their own process: 3.21 s against 0.26 s unfiltered on 12,447 rows at dim 4096, and past their 10000-candidate cap the answer was short, so their API carried a scan_capped flag whose value depended on the query VECTOR. Design: a PRE-filter. repeated Filter filters = 5 on SimilaritySearchRequest; DocumentStore::scan_vectors_filtered (LMDB override) resolves the matching ids in ONE read transaction with the vectors - matchingIdsTxn reuses scan()'s judge verbatim (the index planner planIndexCandidates, every candidate re-judged with matchesFiltersResolved, the whole-document path for SEARCH), then mdb_gets each id's vector and feeds the unchanged scoring lambda. So the answer is the true top-K among matching rows, scores bit-identical to an unfiltered search, no cap. The handler re-judges each fetched document (it is read after the ranking scan, so a concurrent write could make it stop matching - and the row predicate rides in filters, so this is also what keeps a hidden row hidden). Degraded mirror: MemoryStore ranks everything and the first topK matches are kept. Ties are now ordered by id (heap comparator (score desc, id asc), replacement on a strictly better pair), for the unfiltered search too: a filtered search visits rows in a different order, and both must agree on which tied row makes the cut. Observable for unfiltered callers only on exact score ties (duplicate vectors). Old-server guard: a pre-2.14.0 server ignores field 5 and answers UNFILTERED - wrong data that looks right - so SimilaritySearchResponse.filters_applied (2) is set by every 2.14.0 server and the client overload throws Client::FailedPrecondition, reason filters_unsupported, when it sent filters and reads false. A response field rather than a version probe: exact, no extra RPC, no version parsing. Client: a NEW overload similaritySearch(collection, vec, topK, minScore, filters); NOT a defaulted parameter on the old one, which would change its mangled name and drop the symbol every installed binary links. ⚠ Found while reading, fixed here: SimilaritySearch gated the collection and then applied neither the row predicate nor the column masks, unlike Get/Find - on a secured project a vector search returned rows and fields find() refuses (vectorapi: not theoretical for them, a function's policy can grant search). Now: masked-filter refusal, row predicate ANDed into the filters, applyMask on each result. Inert until a project is secured; none is. Semantics worth knowing (documented in the guide, unchanged): minScore 0.0 drops NEGATIVE cosines - my own first test expected all 12 matching rows and got 7; SEARCH ignores its field (whole-document substring), here as in find(). Measured (12,447 rows, dim 4096, best of 5, dev container): unfiltered top 500 187 ms; filter matching ~430 rows top 500 78 ms unindexed / 51 ms indexed; top 5 indexed 13 ms; ~1/7 of rows ~90 ms; no match 0.8 ms - filtering makes the search CHEAPER, it scores fewer rows. Tests: tests/load_test/test_filtered_similarity.{cpp,sh} (port 9024, 417 checks). Its oracle: an unfiltered search with topK = every row is the full ranking; restricted to the ids find() returns for the same filters, its first topK must equal the filtered answer - same ids, same order, bit-identical scores, same bodies - for all eleven operators, conjunctions, three queries, topK 1/5/50/500, then again with indexes declared (including EQ-scalar on an array field, where index candidates must be re-judged to come out empty). Plus: fewer matches than topK, vector-less matching rows, no match, an absent field, minScore after the filter, ties, the qualified name, empty filters, a collection without a dimension, and that the filtered top-K reaches rows outside the unfiltered top-K (the oracle is not vacuous). old <addr> phase run against the released 2.13.1 image in a scratch container: refused with filters_unsupported, plain search still works (4/4). test_policy_enforcement +6 (row predicate, mask, a filter cannot widen past the predicate, masked filter refused, stranger denied). Each part reverted alone: post-filter instead of pre-filter 120 fail; no tie-break 34; no row predicate / mask on the search 3. ABI: one method added, no public type changed, soname 2.connect() connects. (1) Write-time size guard. smartbotic-vectorapi grew a row past the gRPC send limit with small patches (insert 60 MiB, patch +20/+10/+10, every request accepted) and the row could then never be read or exported. MemoryStore::setMaxDocumentBytes (set by DatabaseService to max_send_message_size_mb less a 256 KB margin for metadata and a vector sent alongside) makes patchDocument measure the MERGED body as the JSON text a read sends (doc_binary::to_json_text(encode(merged))) before anything is mutated, refusing with PatchRefusal::Kind::TooLarge; DatabaseGrpcImpl::refuseUnreadableBody refuses an insert/update/upsert body over the limit before parsing, and BatchInsert counts such an item as an error. Both answer INVALID_ARGUMENT, reason document_too_large (retrying cannot help). Rows already over the limit stay unreadable (export row_too_large, get message_too_large). test_export now seeds with the default 100 MB send limit and runs every later phase at 2 MB, modelling exactly that legacy state. (2) A timed-out write. The client retried every write on DEADLINE_EXCEEDED, but the deadline can expire while the server finishes the write (vectorapi: every large patch reported failure and had been applied), so a retry repeated a write that happened - an id-less insert duplicates the row, an increment counts twice, an insert with an id / a conditional write / a delete reports a false AlreadyExists / version conflict / not-found. retryableStatus(s, idempotent) now retries DEADLINE_EXCEEDED only for a plain patch and an upsert with an id; UNAVAILABLE/RESOURCE_EXHAUSTED still retry (the server did not act). Every write ending in DEADLINE_EXCEEDED carries reason outcome_unknown (outcomeUnknownDetail), and writes get setWriteDeadline: timeoutMs plus 1 s per 4 MiB. Consumers that map DeadlineExceeded to "retry as-is" must not do so for writes. (3) update() retried EVERY refusal, not only version conflicts - read-only, memory pressure, a size refusal, an outage - maxRetries times, then logged "failed after N retries due to version conflicts"; found by the size-guard test's own log line. It now re-reads only on Aborted (or a pre-2.12.0 server's in-band Unknown + "Version conflict", the one text the library recognises so callers never have to); FailureSink::copy carries the inner reason out. Not pinned by a test (the observable answer is the same either way; only the wasted calls and the false log line differ). (4) connect() was not a reachability check (reported by smartbotic): creating a gRPC channel opens nothing, so it returned true and logged "connected" against a dead port. It now WaitForConnected up to timeoutMs and returns false when unreachable; the client stays usable (gRPC reconnects on later calls). isConnected() counts IDLE/CONNECTING only if the last attempt succeeded (reached_) - against a SIGSTOPped server the kernel accepts the TCP connection and the channel sits in CONNECTING, which the first cut still reported as connected; the frozen-phase test caught it. ⚠ Observable - a LATENCY change, not an error shape: with the server down, connect() now takes up to timeoutMs and returns false. smartbotic-vectorapi found what that breaks: a boot loop bounded by an ATTEMPT COUNT (for 30 tries: connect(); sleep 1s) went from ~30 s to up to 180 s, past its systemd TimeoutStartSec=90, so a service started while the database is down (every package upgrade's postinst) is killed mid-start instead of exiting cleanly. Their fix was a wall-clock deadline; the guide now warns about this shape. Lesson for consumer notes: list calls that got slower or now block, not only errors that changed shape. Tests: test_read_failures frozen phase (writeRetries=2 at 500 ms, so timing separates a retry from none: plain patch >= 1.4 s, insert/increment/remove < 1.2 s, all outcome_unknown) and connect checks in every phase (54 / 64 / 56); test_export guard checks (insert, upsert, update and a growing patch refused, the row untouched). Each part reverted alone: patch guard 2, body guard 4, idempotency rule 3, outcome_unknown 3, connect() 2. ABI: additions only, soname 2.get/find/similaritySearch never returned a stored embedding (the server moves _vector into _vectors_<collection> on write), so an export of a vector collection would have produced rows that re-import as unsearchable JSON. Design agreed with them before any code (docs/integration-guide.md, "Reading vectors back, and exporting a collection"). (1) Read-back: get/find overloads taking a Client::WithVector tag (a tag type, not a bool or a QueryOptions member, so nothing existing changes size or meaning) return "_vector": [floats], the field insert takes; wire: include_vector on GetRequest (3) / FindRequest (7), raw float32-le bytes in Document.vector (13), sent only when asked. Not on a view. (2) ExportCollection (server stream) + Client::exportCollection(): ONE collection, never a project - vectorapi runs one client for every tenant and its tenancy is a collection-name prefix inside default, so a project-scoped export would have handed one tenant every tenant's rows; gated as an ordinary READ (masks, row predicates), not admin. One stream is one LMDB read transaction (LmdbDocumentStore::export_scan): an exact snapshot in id order whose header rows_at_snapshot is computed in the same transaction, so rows_sent == rows_at_snapshot checks it (a row predicate is applied to the count too). Resume via after_id is a new snapshot strictly after the cursor (MDB_SET_RANGE, so a deleted cursor id works): never repeats, can miss a row inserted behind the cursor. Header carries dimension, dtype float32-le, the clamped batch size (default 256, max 1024, and every batch also cut at 8 MB) and the 600 s stream cap that ends a stream with complete=false + cursor (an open read txn pins pages). Capped at 8 concurrent exports (LMDB's reader table is 126). Refused: vectors from a vector_dimension 0 collection (INVALID_ARGUMENT, reason no_vector_index), a view, a system collection, a degraded mirror (FAILED_PRECONDITION rather than serving a MemoryStore cache that may have evicted rows). A row larger than the listener's send limit ends the export with RESOURCE_EXHAUSTED, reason row_too_large, conflicting_id = the row (rows before it are delivered, resuming after it continues) - before this check gRPC itself failed the write with a nameless RESOURCE_EXHAUSTED, so a caller could not tell which row to skip; batches are cut at min(8 MB, half the send limit) so a batch always fits. Size refusals get a reason (asked by vectorapi): gRPC refuses an oversized message itself, either side, with RESOURCE_EXHAUSTED and no detail - indistinguishable from a rate limit or memory pressure, though retrying never helps; makeDetail now sets reason message_too_large when that code arrives with gRPC core's "message larger than max" text and no server detail (the library owns the text dependency so no consumer matches on it). ⚠ Found by vectorapi on the scratch server, NOT fixed in 2.13.0: a row can grow past the send limit through repeated patch calls (insert 60 MiB, patch +20/+10/+10 - every request small and accepted), after which get fails message_too_large and the export refuses it as row_too_large; a write-time size guard is ROADMAP work. Also observed there: each of those large patches reported DeadlineExceeded to the client and had been APPLIED (the client's deadline expired while the server finished), then the client retried - harmless for an idempotent patch, wrong for anything that is not; recorded as ROADMAP work. The client THROWS when a stream ends without its trailer (a partial export must never look whole), on an unrecognised dtype (never reinterpreted), and on a trailer/row-count mismatch; a handler returning false stops AFTER that row, which is lastId. Per-row VectorState, reported faithfully, never collapsed by the library (vectorapi's explicit request): Present, None (written without a vector, or an update() without _vector removed it - update replaces the whole document), Missing (written WITH one, entry gone: data loss), Unknown (no entry and no marker: a pre-2.13.0 row). The stored body cannot tell None from Missing, so Document::hasVector (std::optional<bool>) records it, written by toJson() (so WAL, snapshot and the LMDB envelope carry it) only for collections with a dimension, read tolerantly by fromJson() (an older binary ignores it). Set by MemoryStore::replaceVectorChange() for insert/update/upsert/updateIfVersion; restore of a deleted row sets false; a write that KEEPS the vector (patch without _vector, in-place restore) stamps an unmarked row from storedVectorExists(), which asks the LMDB vector sub-db - not coll.vectors (this entry first said "because eviction drops a vector from memory"; that was FALSE until 2.21.2 - eviction left vectors resident - and is true, with a reload that restores it, from 2.21.2). That last part was missing in the first cut and found by vectorapi's pre-release run at scale: patch left a legacy row unmarked, so it stayed Unknown forever and could never report Missing if its vector were later lost - real damage reported as ambiguity on exactly the oldest rows - and the documented remedy ("any write stamps it") was false for the most common write. Pinned by test_dual_write_mirror (legacy rows planted directly, vector deliberately not in memory; patch stamps true/false on disk and in memory; a vector lost afterwards reports Missing). (3) Defect: a document and its vector were TWO LMDB commits, so any snapshot between them saw the row without its vector - transiently unsearchable, and an export would have reported real-looking Missing. Now DocumentStore::put_with_vector(collection, id, doc, VectorChange) (storage/vector_change.hpp; Keep/Put/Remove), overridden by LMDB with one WriteTxn (commit, then cache - the v2.8.0 rule), threaded through mirrorDocOrUndo/applyDualWriteMirror for every replace-style write and patch; a refusal (UniqueViolation, MissingParentReference) aborts both. A virtual on the base rather than a dynamic_cast in the mirror, because the unit-test targets compile memory_store.cpp without the LMDB store. (4) Defect: a write body's read-metadata names were STORED. insert/upsert/update/patch kept _id/_version/_created_at/_updated_at/_created_by/_updated_by as ordinary user fields, and every read hid them by overwriting them with the real metadata - invisible, unfilterable (a filter on _version resolves to the metadata), and carried into any export; a get-then-insert round trip wrote six shadow fields per row. Found by planting "mallory" and grepping the LMDB file and WAL. stripReservedFields() (document.hpp) now runs in all five body-taking handlers; the export also strips copies older rows hold. Restore paths (RestoreVersion/RestoreToDate) take no body and are unchanged. A restored row gets FRESH metadata (agreed with vectorapi: no preserving write mode, which would let a caller forge _created_by); the originals are in the archive. (5) Consumer-reported, closed here: deleteFile/setFileTtl answered a bare false for "no such file" AND for a failed call - the 2.12.4 sweep missed them because they are writes with no Failure& channel; they now have Failure&/FailureDetail& overloads (NotFound vs the real code). And subscribeEvents' reader thread called handler(out) (and parsed the event) with no try: one throwing handler terminated the consumer process; it now logs and drops that event. ABI: soname 2; no existing public type changed size; only additions, and the removed exports are private Client::Impl members. Tests: tests/test_export_scan.cpp (30, store level: the four states incl. Missing/Unknown written directly, order, resume incl. a cursor between ids and past the end, the count under a predicate, put_with_vector replace/remove/keep, the marker through toJson/fromJson, and a concurrent writer+exporter); tests/load_test/test_export.{cpp,sh} (port 9023, 85 checks + an on-disk check: read-back, header/clamp/order/count/states/exact bytes, THE ROUND TRIP - export, insert into an empty collection, same fields, byte-identical vectors, each sampled row its own nearest neighbour, fresh metadata - resume, refusals, the payload edges under a 2 MB send limit (300 KB rows batched by bytes; a 3 MB row refused by name, the rest resumable), the file overloads, a throwing handler, a restart, a concurrent-insert race, an outage). Each part reverted alone: strip - the planted value reaches the data directory; marker - 1 e2e + 6 unit checks; handler guard - the e2e process aborts; file overloads - 2; oversized-row check - 1 (gRPC's own nameless refusal); two-commit write - 16,592 false Missing rows over 71,925 concurrent store-level exports (0 with the fix, over 8.36 M rows). ⚠ Honest test limitation: the e2e race phase CANNOT see the two-commit revert (0 hits in 1,353 exports even with a 2 ms sleep injected between the commits), because the export handler's getCollectionInfo() takes the collection's shared lock, which a writer holds across both commits - so on this path an export's snapshot almost always begins between writes. The window was real for readers that take no such lock; the store-level test is the evidence, the e2e phase only pins the invariant. Pre-release run by smartbotic-vectorapi before the tag (branch feat/v2.13.0-export, scratch server on 127.0.0.1:19023): 12,948 synthetic rows at dimension 4096 (~195 MiB), ids adversarial for memcmp order, seeded partly on 2.12.4 so legacy rows exist, then the same data directory swapped to the branch. Export probe 36/36 (header, checksum, byte order, extremes, states, stop + resume with zero duplicates, cursor past the end, clamp); the round trip clean (fields exact, vectors byte-identical, fresh metadata, searchable); MISSING manufactured with a one-off tool on twelve rows (server stopped), split six stamped / six unstamped: exactly six Missing and six Unknown, the other 12,712 vectors byte-identical, and their import refused all twelve. It found three defects: patch did not stamp (fixed in e5bc567), and the two ROADMAP 5b-3 items. Note on evidence: their patch of legacy rows after a restart shows the stamp records the right value, NOT that it reads from disk (a restart reloads vectors into memory); only test_dual_write_mirror (vector deliberately not loaded) covers the disk read.Client::get returned nullopt for every failed status except PERMISSION_DENIED, so UNAVAILABLE/DEADLINE_EXCEEDED was the same value as "no such document". Their collection lookup is one get; a blip became "no such collection", which a careful client cannot retry (retrying every 404 retries every real absence), and a consumer lost a six-minute ingest of an 8 GB mailbox to it. Wider than reported, found by checking every read: exists (false), count (0), find/findWithMetrics (empty - they threw only on NOT_FOUND, and a survey subagent claimed they already threw on everything, which was false), setMembers, setIsMember, both version reads, every list read, getCollectionInfo, getViewInfo, getRelationInfo, hasCollectionConfig (false) and getCollectionConfig (silently the DEFAULTS). v2.4.2 and v2.8.0 had applied the rule one status code at a time. The rule now, written above throwStatus in client.cpp: a read whose "nothing there" value is also a valid answer THROWS Client::Error on ANY failed status. Safe because the server reports every absence IN-BAND (found=false, exists=false, empty lists) - only Find uses a NOT_FOUND status, and that already threw - checked handler by handler before changing anything. Exempt by design: healthCheck (false), getHealthInfo/getStats (nullopt), getRelationsEnforced (fails toward true), tryGetRelationsEnforced (declines); writes keep their return values. update() had the same bug on the write side: it reads first through get, so an outage was reported as NotFound "document not found"; it now catches the read's Client::Error and records the real code (a permission denial still throws out of it, as before). ⚠ ERROR-SHAPE CHANGE under an unchanged soname, decided by the owner over additive overloads: code that called these reads without a try now sees a throw during an outage, as soon as the library is upgraded. A consumer survey found one place where that is fatal - smartbotic webserver's scheduler thread calls get through StorageClient (webserver_service.cpp:170 via workflow_scheduler.cpp:355) with no catch, so a DB blip would terminate the webserver; also smartbotic's StorageClient (get/getCollectionInfo/getVersion/listVersions forward without catching, against its "never throws" Result contract) and the runner's QuickJS js_storage_get binding. Consumer sessions were notified with those sites; smartbotic must catch there before its hosts take this library. (Corrected by smartbotic after checking its own code: the scheduler lambda and the QuickJS binding already handled a failed Result, so neither was fatal on its own; the single gap was the StorageClient adapter not catching, through which the throw would have escaped. Its query() was worse than unguarded - it caught std::exception and answered CollectionNotFound, the same bug one layer up. Patched and deployed on 2.12.4.) shadowman-cpp (its InstrumentedDbClient now sees read failures, so its circuit breaker finally counts them) and vectorapi already handle read exceptions. Same rule, second consequence: a non-admin's DENIED schema read on a secured project (listRelations, getRelationInfo, ...) now throws PermissionDenied instead of answering empty - test_policy_enforcement asserted the empty answer while its own comment said it meant to prove "a real denial, not 'not found'", which an empty answer cannot show; it now asserts the denial. Inert unless security is enabled, which no deployment has. ABI: no type or signature changed. Test: tests/load_test/test_read_failures.{cpp,sh} (port 9022) drives 24 reads through three server states - up (every genuine absence still empty and NOT thrown, 52 checks), SIGSTOPped (the blip: DeadlineExceeded, 54) and stopped (Unavailable, 54) - and pins update()'s code and the exempt reads. Reverting the client fails 49 of the 54 frozen-phase checks; the absent phase passes either way, by design.dropProject never touched files - records live in a global tree under <filesDir>/records, not in the project's env - so a dropped project's files survived and were served to a later project of the same name; the third member of the class 2.12.2 closed for configs and documents. DropProject now calls FileManager::deleteAllIn(project), one record at a time through the refcounted deleteFileIn, so a blob another project also references survives (asserted, across a restart). (2) The upload size limit (storage.files.max_file_size_mb, default 500) was checked in storeFile() only after UploadFile had buffered the ENTIRE body, so an oversized upload cost its full size in memory (times max_concurrent_file_streams) before being refused - and the refusal, a bare runtime_error, surfaced as INTERNAL. Now the handler refuses mid-stream (INVALID_ARGUMENT, reason file_too_large, max_bytes in the detail); storeFile throws a typed FileRejected for that and for mime_type_not_allowed. Measured: a 64 MB upload against a 1 MB cap raises the server's peak RSS by 5 MB with the fix, 81 MB with it reverted. (3) DownloadFile read the whole file into memory before streaming it out; it now streams from the blob on disk in 64 KB chunks (blobs are stored uncompressed). Answers that needed no change: identical bytes share one refcounted blob, so deleting one record of two is safe; file content is on disk, outside MemoryStore and max_memory_mb; names are not unique (listFiles has an exact-name filter). Uploads are still buffered whole in server memory up to the limit, and the client API is whole-buffer both ways. No wire or client API change (the client's upload refusal now carries its detail). Test: tests/load_test/test_file_store.{cpp,sh} (port 9021, 1 MB cap + a MIME allow-list): a VmHWM check on a fresh server, 18 checks, 3 after a restart. Reverted alone: typed refusal 1 fails, project file deletion 2, size check while streaming fails the memory check (it was invisible to every functional assertion - the refusal looks the same either way, which is why the memory check exists). The streaming download has no memory check (at a 1 MB cap the difference is not measurable); its correctness is pinned by byte-for-byte equality.dropCollection removed the documents but not the collection's CONFIG record in _collection_meta (indexed fields, unique fields, composite constraints, relations_enforced, versioning, precision), nor its _idx2_/_uniq1_ sub-dbs, and the store stayed armed to maintain them. A later collection of the same name silently inherited a unique constraint nobody declared (a legitimate write refused as a duplicate, and re-declaring it answered already_existed instead of validating the new data). And once the collection's project was gone the record was unremovable: DropIndex refused without an LMDB store ("secondary indexes require the LMDB substrate"), dropCollection said false. Fix: CollectionConfigManager::removeConfig(); DatabaseGrpcImpl::purgeCollectionDeclarations(name) disarms the store, removes the record, then drops the index and composite sub-dbs, and DropCollection runs it even when the collection no longer exists, so it also repairs an already-poisoned name; DropIndex undeclares with or without project storage. dropProject was worse than reported, found by the test: it removed the project's LMDB env but its collections stayed in MemoryStore and the WAL, so the "dropped" data was still served (re-inserting a dropped id said "already exists") and a restart would replay it. DropProject now, only after the project drop succeeds (it refuses default, so purging first could destroy data a refused drop meant to keep), drops each of the project's collections like DropCollection does - MemoryStore, a WAL drop record so replay cannot resurrect it, and its declarations - and DatabaseService::dropProject removes every remaining config record under the project prefix, which catches declarations on collections that never had documents. No wire or client change. Test: tests/load_test/test_drop_cleans_declarations.{cpp,sh} (port 9020, 26 checks + 11 after a restart), including the poisoned state older versions left behind, recreated by writing a config record for a storage-less project straight into _collection_meta and restarting. Each part reverted fails it: collection purge 6, DropIndex without storage 2 (after the restart), project-wide config purge 1, project in-memory drop 1. ⚠ Process lesson, nearly a false result: a revert loop that restores sources must REBUILD before the next run; one loop here left a reverted binary in build/, and the next "verification" was testing it.AlreadyExists rather than Internal (MemoryStore::insert threw a bare runtime_error). Checking where that duplicate check looks found the first half, which is far worse and predates 2.12.0: the check reads coll->documents only, and eviction moves a document out of it into evictedDocs_. Since v2.0 reads are served from LMDB, so a read no longer hot-loads an evicted document - nothing ever brought it back, and every write path (insert, update, updateIfVersion, upsert, patchDocument, remove, setAdd, setRemove, restoreToVersion) looked only in MemoryStore. Measured on 2.12.0 with real eviction, 200 of 200 each: patch "not found"; remove returned false and the document stayed; insert with the id was accepted and overwrote the existing document (the LMDB mirror mdb_put has no NOOVERWRITE); upsert re-created it at version 1. Reachable wherever eviction fires: the packaged default budget is 512 MB and the estimator runs ~5x low (v2.4.3), so a default install with a few hundred MB of data evicts; the production instance ran an 8 GB budget at 0% and was not exposed. Fix: MemoryStore::reloadIfEvicted(collection, id) in every write path, AFTER its InFlightWriteGuard (so the reloaded document cannot be evicted again before the write - eviction skips in-flight ids) and before the lookup; it reloads through the existing loadEvictedDocument() and fails closed - if a stub exists and the reload fails, the write throws instead of treating the document as absent, because treating it as absent IS the bug. Duplicate id: a typed DuplicateDocumentId (a runtime_error with the old message, so internal callers are unaffected); the Insert handler answers ALREADY_EXISTS with detail reason duplicate_id, conflicting_id = the id, fields empty (no field collided, the identity did). BatchInsert still reports per-item failures only as a count, unchanged. No wire or client change. Tests: tests/load_test/test_evicted_writes.{cpp,sh} (port 9019) runs the server with a 1 MB budget and no hot-write floor so eviction really happens - it asserts eviction occurred, else the test would prove nothing - and puts each kind of write on its own collection so every operation meets genuinely evicted documents. Reverting the reload fails 7 checks (150/150 each); reverting the duplicate mapping fails 4. update alone survives the reload revert, only because the client retries and the 2.12.0 refusal path happens to read (and so reload) the document in between./tmp/db-changes-for-vectorapi.md, D1-D7). Checked against source first, which corrected one: D7 ("reading a version costs a history call") was already solved - get(), find() and findWithMetrics() have always attached _version (client.cpp), so vectorapi's claim can drop its getVersionHistory round trip; documented, no change. (D1) A refusal says WHY, in a form a program can branch on. Every refused write may carry trailing metadata sbdb-error-detail-bin (UTF-8 JSON; contract above service DatabaseService in the proto): reason (unique_violation / missing_parent / delete_restricted / read_only / memory_pressure / view_write / not_found / version_conflict / invalid_increment), fields, values, conflicting_id, relation, current_version, and code for in-band refusals. Trailing metadata, not a response field, because it works for error statuses AND in-band replies alike - gRPC's C++ sync server sends no response body with an error status. The reason also fixes a real ambiguity found on the way: FAILED_PRECONDITION meant a missing parent, a restricted delete AND read-only mode, so a consumer mapping it to "relation violation" mislabelled a read-only database. UniqueViolation now carries fields (vector, for composites) and values. Client: new Client::FailureDetail {code, message, reason, fields, values, conflictingId, relation, currentVersion} with FailureDetail& overloads beside every Failure& one, plus static Client::errorDetail(const Error&) for the throwing calls. The thrown objects are INTERNAL subclasses (DetailedAlreadyExists : Client::AlreadyExists, DetailCarrier, ...) and errorDetail cross-casts to the carrier - so no public exception class changes size (a consumer copying one with its own inline copy constructor would otherwise slice the new members off or worse), and a 2.11.4 catch (const Client::AlreadyExists&) still matches. Internally one FailureSink {Failure, FailureDetail} replaces the 2.11.4 Failure* parameters so both overload families record a failure identically. In-band refusals got codes: UpdateResponse/PatchDocumentResponse.error_code (4) carries the code the refusal would have as a status (NOT_FOUND, ABORTED, FAILED_PRECONDITION, RESOURCE_EXHAUSTED, INVALID_ARGUMENT); they stay in-band so pre-2.12 clients see exactly what they did. Closes the 2.11.4 known limit. updateIfVersion used to report a MISSING document as "Version conflict" too; the message is kept (old clients may match it) but the code now says NotFound. (D2) patchIfVersion: optional uint64 expected_version on PatchDocumentRequest (6), checked under the collection lock; a stale version is a real ABORTED status (only callers that send the field can see it) with current_version in the detail. Needed because updateIfVersion replaces the whole body, so a one-field claim reverted any concurrent change to other fields. (D5) increment(): increments_json (7) on PatchDocumentRequest, new values back in incremented_json (5). Absent/null = 0, dotted paths create objects, int+int stays int with overflow refused, otherwise double; non-numeric value or delta, metadata paths and a path the merge patch also sets are refused with INVALID_ARGUMENT/invalid_increment. The merge and the increments are now computed on a COPY before anything is mutated (patchDocument used to merge after saveToHistory and the expiry-index removal), so a refused increment leaves the document, its history and its expiry untouched - asserted by checking a valid increment in the same call was NOT applied. Missing document is NotFound; no upsert, by decision (documented pattern: increment, on NotFound insert under a fixed id, on AlreadyExists increment again). (D3) Null is not a value for uniqueness (SQL): skipped in the unique check and in find_duplicate_values, but still indexed so EQ null is served. Strictly more permissive, so it cannot invalidate existing data. Note patch with null REMOVES a field (RFC 7396) - my own first test got that wrong. (D4) Composite unique constraints: CreateIndexRequest.fields (4) / DropIndexRequest.fields (3) / IndexInfo.fields (5); CollectionCfg::compositeUniques in _collection_meta; one plain (not DUPSORT) sub-db per constraint, _uniq1_<collection>#<f1>+<f2> (+ and \\ escaped so distinct lists cannot share a name; trailing 1 = key format version), key = the tuple of encode_index_key forms each with a 4-byte length prefix (so ("ab","c") != ("a","bc"), asserted), data = holder id. Any component absent/null/object/array = not constrained. Enforced and maintained in maintainIndexes, in the document's own write transaction. ⚠ Three things that were easy to get wrong: (1) can_reject_writes() gates MemoryStore's undo snapshot and had to count composite constraints - otherwise a refused write stays applied in MemoryStore while LMDB rolls back (asserted: a refused insert leaves its id free, a refused update is not resurrected by a later unrelated patch); (2) both write-path gates (needs_index) skipped maintainIndexes for a collection with no indexed field, i.e. a composite-only collection; (3) the builder must scan AND populate in ONE write transaction, after arming - my first version read rows in a read txn and wrote in a later write txn, so a write landing between them would be wiped by the rebuild's mdb_drop. Armed first, a write after arming maintains the constraint; LMDB's single writer means the build sees every earlier commit. Refused declarations disarm. Re-armed and self-healed at boot. Client: createCompositeUniqueIndex / dropCompositeUniqueIndex / listCompositeUniqueIndexes - separate names because {"a","b"} would also bind to createUniqueIndex's std::string (as an iterator pair) - and listIndexes() skips composites so the display form a+b is never mistaken for a field. CLI: unique-create, unique-drop, indexes lists them. (D6) removeManyAs(collection, ids, actor, FailureDetail&) exposing BatchDelete, which no client method reached; BatchDeleteResponse.deleted_ids (2) in request order, so the server now removes per id rather than via bulkDelete's count-only loop. Tests: tests/load_test/test_db_changes_for_vectorapi.{cpp,sh} (port 9018), 87 checks, a real restart, 7 more after it - including 8 concurrent patchIfVersion claims of one version (exactly one wins) and 8x50 concurrent increments (exactly 400). Each part reverted on its own fails the test: null rule 2, MemoryStore undo gate 2, boot re-arming 1 (after the restart), version condition 4, detail trailer 29, in-band codes 6. Release note: this release also carries the event-actor work prepared as 2.11.5 and never published (next entry), so 2.11.5 does not exist as a package; vectorapi's floor >= 2.11.5 is satisfied by 2.12.0.actor (fn:<project>/<id>:<depth>) and refusing past a depth. Client::remove() had no actor parameter and DeleteRequest no field for one, so a function's delete was indistinguishable from a human's. It was worse than the report said: even for inserts and updates the event carried no actor at all (DatabaseEvent had none, and its body is doc->data(), the user fields only), so vectorapi read provenance back from version history afterwards - racing any later write - and a delete leaves no usable trace there either, because the history entry it saves is the PRE-delete state, whose updated_by names the last writer, not the deleter. Fix: actor on DeleteRequest (3) and BatchDeleteRequest (3), and on every DatabaseEvent (7), sent whether or not the subscriber asked for data. Client: removeAs(collection, id, actor[, Failure&]) and subscribeEvents(collections, handler) delivering a new Client::Event {collection, id, eventType, data, actor, timestamp, nodeId}; the old subscribe() is now a thin adapter over the same reader loop. removeAs is a separate NAME on purpose: remove(collection, id, someString) already binds to the std::string& errorOut overload, and C++ prefers that for a non-const std::string - an actor overload would have compiled and silently cleared the caller's actor instead of sending it. The actor is explicit-or-derived (std::optional<std::string> through PersistCallback, emitPersist and notifyReplicationAndEvents): a value, even empty, is used as given; nullopt takes doc.updatedBy. Deriving is correct only where a write stamps updatedBy fresh from its request - insert, update, upsert, conditional update, restore all do. Three places it is NOT, each a misattribution the e2e pins: (1) patchDocument deliberately KEEPS the previous updatedBy when a patch carries no actor (stored audit behaviour, unchanged), so its event passes the request actor explicitly - deriving reported the last writer as the patch's author, which would make an ordinary client patch look like a function's write; (2) a relation cascade passes the DELETING caller's actor for the parent and every child it deletes or nulls - a set_null child still has its previous writer in updatedBy; (3) TTL expiry and TTL-driven cascades pass an explicitly EMPTY actor. Found by the test, not by reading: the first build put the actor on the internal event but not on the wire (Subscribe copies fields one by one), so all 13 actor assertions saw empty; and the patch misattribution above. Tests: tests/load_test/test_event_actor.{cpp,sh} (56 checks over real gRPC, both subscription forms side by side). Reverting the client send fails 6, the server Delete/cascade plumbing 6, the explicit patch actor 1, the wire copy 13. ABI: 31 public types byte-identical to 2.11.4, nothing public removed, three methods added, soname 2; a test binary built entirely against 2.11.4 (33/33) and the released 2.11.4 CLI both ran on the new library. ctest 23/23, 12/12 e2e. Consumer note: vectorapi's current history lookup (triggeringDepth) has the patch misattribution today - an actor-less patch after a function's write reads the function's actor from history; reading Client::Event::actor fixes that and the delete case together.relations_enforced is write-only" - it was not. Client::getRelationsEnforced() has shipped since v2.11.0 and was in the header the consumer already built against. They looked on CollectionInfo / GetCollectionInfo; the setting is served by GetCollectionConfig. What made a careful reader miss it was ours: the integration guide did not mention relations at all, the CLI could set the flag (configure-relations <c> <on|off>) while no command could show it, and nothing near CollectionInfo said where changeable settings live. Fixed all three: a guide section, configure-relations <collection> with no value reads, info prints relations_enforced, and comments on getCollectionInfo() and the proto message point at the right RPC. The requested third state ("never configured") was declined: the report's own reason for it was that unset and explicitly-disabled look alike, and they do not - one reads true, the other false. The two states a bool merges, unset and explicitly-on, behave identically, and every config record written since 2.11.0 already carries the key, so it could not be recovered anyway. One real weakness was found on the way: getRelationsEnforced() answers true when the read itself fails, which is right for code relying on enforcement and wrong for a UI toggle - the exact "a switch would have to invent its position" complaint. Client::tryGetRelationsEnforced() returns std::optional<bool> where no value means "could not be determined" (any failed status, or a pre-2.11.0 server, which never sets the field). It does not throw on PERMISSION_DENIED, unlike get()/find(): those throw because their empty result is a valid answer a denial could be mistaken for, and no-value cannot be mistaken for on or off. (2) "The client erases gRPC status codes" - true, and wider than reported. The server has returned ALREADY_EXISTS for a unique violation and FAILED_PRECONDITION for a missing parent or a restricted delete since v2.11.0, and the client then dropped the code: a duplicate key reached an HTTP caller two layers up as a 500. The report named insert, update and patch as throwing. Only insert/upsert/find/the file calls throw; update, updateIfVersion, patch, patchWithTtl and remove return false or 0, so the typed exception the report asked for would have fixed POST and left PUT and PATCH exactly as broken. Both shapes are covered. Throwing calls now throw Client::Error (carries code()), with Client::AlreadyExists / FailedPrecondition / PermissionDenied as subtypes; it derives from std::runtime_error with what() unchanged, so every existing catch block behaves as before. Return-value calls gained overloads taking a Client::Failure& ({code, message}), the same shape as the v2.11.0 remove(..., std::string& errorOut) - they cannot start throwing without turning every existing if (!db.update(...)) into an uncaught exception. Everything is nested in Client (Client::ErrorCode, not a namespace-level StatusCode/ErrorCode), because a consumer with using namespace smartbotic::database and its own ErrorCode - smartbotic-automation has one - would stop compiling. Client::ErrorCode mirrors grpc::StatusCode number for number so the header still needs no gRPC include. The exception types are defined out of line so their typeinfo lives in the library and a throw inside the .so and a catch in the consumer agree on the type by construction. ⚠ Known limit: Update and PatchDocument refuse some writes in-band (status OK, success=false, a message - not found, version conflict, read-only, memory pressure, view write); those carry no code on the wire and arrive as ErrorCode::Unknown with the text. update() alone reports a missing document as NotFound, because it reads first and knows. Closing the rest is a wire change; see ROADMAP 5b-2. ABI: only methods and nested types were added. All 30 public types compared byte-identical against the v2.11.3 header, soname still 2, the only removed exports are three private Client::Impl members and two inline spdlog instantiations, and a test binary built entirely against 2.11.3 plus the released 2.11.3 CLI both ran against the new .so (33/33). Tests: tests/load_test/test_client_error_codes.{cpp,sh} (33 checks; each condition is driven through several calls so a fix to insert() alone fails - 17 of 33 fail with the propagation reverted), test_relations_client_e2e 33 -> 46 plus 8 CLI checks, each read asserted in both states so a constant fails (4 of 46 and 5 of 8 fail with the read mapping reverted). ctest 23/23, all nine client/server suites green. ⚠ A host that cannot build the project natively uses packaging/dev.sh (see Build). Found the hard way here: the build/ tree had been made in a container that mounted the repo at a fixed path which no longer existed on the host, so a host cmake --build build failed AND created that path as an empty stray directory, and a host cmake -B build overwrote the cache with host paths. dev.sh mounts the checkout at its own path instead, and build.sh --local now reconfigures a tree that was configured elsewhere or by another system's CMake. In the same pass build.sh lost its hardcoded /data/smartbotics-deb-repo default (it now uses $DEB_REPO_DIR, else a smartbotics-deb-repo checkout next to this one, and checks before building - it used to fail only after a full package build), and --repo stages only the packages the run produced instead of every .deb that has ever accumulated in dist/.stopGrpcServer() called grpc::Server::Shutdown() with no deadline. That form waits for every in-flight RPC to return and cancels nothing — and Subscribe never returns on its own: its handler parks in while (!context->IsCancelled()), and that context is cancelled only when the client disconnects or a shutdown deadline expires. So any consumer holding an event stream — the normal state of one — blocked the stop indefinitely. The damage was not the slow stop. stop() calls stopGrpcServer() FIRST and takes the final snapshot AFTER it, so the hang blocked the snapshot too; systemd then SIGKILLed at TimeoutStopSec=300, and the next boot recovered by WAL-only replay, which trips auto read-only mode and needs an operator smartbotic-db-cli unlock — i.e. a graceful restart looked like a crash to the next boot, and the v1.8.0 "final snapshot so recovery is trivial" guarantee silently did not hold for anyone using events. Fix: an absolute 5-second deadline shared across listeners (so the total wait is bounded by the grace period, not grace × listener count); once it expires gRPC cancels what is still running, the Subscribe loops observe IsCancelled() and unwind. Five seconds because an ordinary unary RPC finishes in milliseconds and the snapshot — the part of shutdown that legitimately takes ~70 s on the largest known dataset — dwarfs it either way. Reported by a sibling project that hit the same gRPC trap in its own code, not by our tests, and that is the lesson: nothing in the suite ever stopped the service with a stream attached. tests/load_test/test_shutdown_with_subscriber.sh now does, and asserts the three things that matter in order — the process exits on SIGTERM with a subscriber attached, the final snapshot is written, and the NEXT boot reports TrivialSuccess and is not read-only. Reverting the deadline leaves the process running past the 30 s budget with Stopping database service... as its last log line; with the fix it exits in 9 s. The loop now unwinds on a SIGNAL, not on the deadline. beginShutdown() sets a flag and notifies a condition variable, and stopGrpcServer() calls it BEFORE Shutdown(deadline), so the streams are usually gone before gRPC is even asked to stop; the deadline is now a backstop rather than the mechanism. Measured: 0 ms between "Stopping database service..." and the handler reporting its close. The 100 ms timeout stays inside the wait because the sync API gives no way to be woken when a CLIENT disconnects, so that half is still polled. ⚠ Fixing the unwind required fixing a writer-lifetime bug first, and it would have been made worse otherwise. EventManager::publish() copies matching callbacks out under its lock and invokes them OUTSIDE it, so unsubscribe() does not stop a dispatch already running — a callback could be writing through writer after the handler returned and gRPC freed it. Narrow before (a client disconnect racing a publish), but unwinding EVERY subscriber at once is exactly what widens it. A per-stream shared_ptr<StreamState>{mutex, open, writer} closes it in both directions: the callback takes the mutex and gives up if closed, the handler closes under the same mutex, so on return the write either finished or never started. The same mutex also serialises concurrent writes from several publishing threads, which grpc::ServerWriter does not permit and nothing previously prevented. Handlers now return UNAVAILABLE on shutdown rather than OK, because OK reads as "your subscription ended normally" and UNAVAILABLE is what a gRPC client already retries on. What is still slow, and is NOT ours: a stop with a client connected spends ~4 s inside Shutdown() draining that client's transport — proven by isolation, since killing the client first makes Shutdown() return in 1 ms — plus a few seconds joining component threads after persistence stops. Both are bounded and unaffected by this change; the test therefore measures the handler's own unwind latency out of the log rather than process wall-clock, which would have been asserting gRPC's drain by accident.encryption.enabled=true) and keys off FIELD NAMES — *.api_key, *.apiKey, *.password, *.secret, *.token, *.credentials — in every collection, independent of the collection-level encrypted flag and of sensitiveFields, which is not what anyone assumes and was documented nowhere. Get/Find/SimilaritySearch/the view branches all decrypt; GetVersionHistory and GetDocumentVersion did not, so a consumer asking "does this document differ from its published version?" compared plaintext against $ENC$... and got yes, forever — a badge that is always on. Fixed with an EncryptionManager::decryptSensitiveFields(DocumentVersion&, collection, id) overload gated on ver.encrypted exactly as the Document overload is gated on doc.encrypted. Note the identical ciphertext across consecutive versions is preserveUnchangedEncryption working as designed (an unchanged sensitive field keeps its stored ciphertext rather than being re-encrypted under a fresh IV, so history shows no spurious diff), not a fixed IV. (2) The same two handlers never applied COLUMN MASKS or the ROW PREDICATE — found while fixing (1), not reported. The v2.8.0 gate comment there says history is gated "or it would bypass column masks"; the gate was added and the masking never was, so on a secured project history returned columns Get refuses. Latent only because security is off by default and no deployment has enabled it. prepareVersionForResponse now decrypts + masks every version body, and gateVersionRow decides visibility from the CURRENT document (a row predicate selects rows, and the row's identity is its current document) and fails closed when that document cannot be read, since "allow because we cannot check" would expose the history of a row the principal was never allowed to see. (3) relations listed nothing while enforcement was active. Client::listRelations() scopes to config_.project, so the CLI — whose default project is default — printed "no relations declared" on an instance whose relations live in another project, while relation <name> (never project-scoped) displayed the very relation the listing denied. An operator asking "what is enforced here" got the one wrong answer that invites declaring it twice. Added Client::listRelations(project) (an OVERLOAD, no struct changes size, soname stays 2) where empty means every project, which is what ListRelationsRequest.project has always documented; smartbotic-db-cli relations now lists every project and --project narrows. (4) relation-create blamed the wrong argument. An unqualified relation name resolves to default like every bare name, so a qualified child and parent elsewhere produced "relation, child and parent must be in one project" — naming the two arguments that were correct. Now an unqualified name ADOPTS the project its child and parent agree on (unambiguous precisely because a cross-project relation is impossible: there is exactly one project it could mean), an explicitly qualified name that disagrees is still refused but the message blames the NAME and prints the form that would work, and the child/parent mismatch message names both sides with the projects they resolved to. (5) Two reported items were WRONG, and checking beats relaying: index-create already accepts --unique (it was simply missing from help, so the operator concluded the headline unique-constraint feature was unreachable from the CLI), and find already accepts --limit (also absent from help). Fixed the help text, and added what was genuinely missing: find --offset N and find --eq FIELD VALUE, so paging and routine cleanup no longer need a client program. --version on every binary: the CLI had none at all — --version fell through to command dispatch and tried to CONNECT, so the one question you ask a binary before trusting anything else needed a running database. smartbotic-db-cli --version now prints its own version and commit and the version/commit of the client library the dynamic linker actually bound, which is the divergence an operator is trying to diagnose; smartbotic::database::clientLibraryVersion()/clientLibraryCommit() expose the same to consumers as free functions. Answers to the questions asked: relation-check uses the reverse index — it walks distinct parent ids (MDB_NEXT_NODUP) and does one mdb_get per distinct parent, so it costs O(distinct referenced parents) and reads no child documents, cheap enough to run periodically; a child field nested inside an array of OBJECTS (nodes[].config.credentialId) cannot be expressed, since path resolution descends objects only — an array of scalars is fine and contributes one posting per element; and "no parent" is already expressible as null or an absent field, which never blocks a delete and never counts as dangling — it is only the empty STRING that is rejected, because that is a reference to a document whose id is "". Tests: tests/load_test/test_version_encryption.{cpp,sh} (8 checks over real gRPC with encryption armed, plus an on-disk $ENC$ grep so a vacuous pass is impossible — 5 of 8 fail with the decrypt call reverted), test_relation_manager 70 → 83.docs/superpowers/specs/2026-08-03-relations-design.md (re-validated 2026-08-09 — read its status section first). Plan: docs/superpowers/plans/2026-08-09-relations-v2.11.0.md. Data model: a relation is a document in the _relations system collection keyed <project>:<name>, exactly parallel to _views, naming child/child_field/parent/on_delete/validate_on_write. Cross-project relations are refused — each project owns its own LMDB env and no transaction spans two. Reverse index: one _relidx1_<name> sub-db per relation, MDB_DUPSORT, key = parent id, data = child id. The trailing 1 is a KEY FORMAT VERSION, paying forward the _idx_→_idx2_ lesson. DUPSORT was chosen over the design's original composite <parentId>\0<childId> keys because mdb_cursor_count gives a parent's child count without reading the children, which is exactly what restrict and DescribeDelete need. Policies: restrict (default) refuses the delete with FAILED_PRECONDITION naming the relation, the child count and sample ids; cascade deletes children; set_null nulls the field; no_action permits and leaves the reference dangling. ⚠ For an ARRAY-valued reference cascade and set_null collapse to the same thing — pull the id, keep the document. Deleting a node because one of its three credentials went away would be worse than useless; this is the one place a MySQL mental model actively misleads. Absent and null are NOT references: they never block a delete and never count as dangling. ⚠ WAL BEFORE LMDB, mandatory: a cascade writes and fsyncs WAL entries for the parent and every child mutation before the single LMDB commit, because MemoryStore is rebuilt at boot from snapshot + WAL and not from LMDB — an LMDB-only cascade would have its child deletions resurrected on the next restart. Consequence to know: a cascade that fails after the fsync returns INTERNAL but still applies on the next restart; that is inherent and documented in relation_cascade.hpp and the error text. validate_on_write rejects a child write whose parent is missing, as an mdb_get on the parent sub-db inside the child's own write transaction — which is what closes the restrict race rather than narrowing it (LMDB serialises the two transactions but the loser simply commits second). Gated by relationsEnforced, because that switch is the escape hatch for a bulk import and a bulk import rejected for missing parents is exactly that case. DescribeDelete(collection, id) reports what a delete would do — which relations apply, child counts, which policy fires, whether it blocks — and would_be_blocked agrees with what a real delete does, including when enforcement is off. A relational DB exposes its constraints through readable DDL; a document store has none, so this has to be answerable as a query. Bootstrap: CreateRelation backfills the index over existing rows, so declaring a relation on a populated collection actually protects it; without that it would look active and enforce nothing for every pre-existing row. relations check reports dangling references and changes nothing. applyRelationDeclarations() re-arms at boot and self-heals a declared relation whose sub-db is absent. Per collection: CollectionCfg::relationsEnforced (default true, optional bool on the wire so a precision-only ConfigureCollection cannot silently disable it) and uniqueFields, both in _collection_meta so they are WAL'd and snapshotted for free. Disabling is NOT retroactive — dangling references created while off are found only by relations check. TTL expiry runs the same on_delete policy as a manual delete (operator's decision, MySQL-style): restrict blocks the expiry so the document outlives its TTL (WARN + ttl_blocked_documents gauge and ttl_expiry_blocked_events counter on GetMemoryStats, because a document silently outliving its retention policy needs a signal an operator can actually read), cascade/set_null route through the real executeCascade, no_action proceeds. expireDocuments() is two-phase so the hook runs lock-free — necessary because unloadDocument/loadDocumentWithHistory reach getOrCreateCollection, which takes globalMutex_ exclusively, and calling that under a shared hold self-deadlocks on a non-upgradable shared_mutex. Unique constraints are now enforced. The check existed since v2.10.0 but was unreachable: it throws from put() inside applyDualWriteMirror, which caught every exception, bumped drift and flipped mirror_healthy_ — so a violation was swallowed (row still in MemoryStore, constraint unenforced) AND sent every read in the process to MemoryStore for its lifetime, the v2.8.1 fault. Now UniqueViolation and MissingParentReference are rethrown without touching health or drift (a rejected write is the caller's business), MemoryStore undoes its in-memory mutation restoring the previous value rather than erasing, handlers map them to ALREADY_EXISTS / FAILED_PRECONDITION, and declaring uniqueness over existing duplicates is refused with examples. ⚠ applyDualWriteMirror has THREE callers and they are deliberately different: the ordinary write path rethrows; the replication-apply path keeps the old swallow-and-flip, because the origin already committed and may not share this follower's config, so discarding would diverge the follower over a constraint the origin never had; backfill guards per row. Txn-accepting overloads (put/del/put_vector/del_vector taking a caller's WriteTxn plus a handle collector, and put_batch) make a multi-collection cascade atomic. ⚠ THE INVARIANT, verified four times and true at all six recording sites: every handle is recorded into to_cache as the statement immediately after open_for_write, before anything that can throw; a txn-accepting overload NEVER caches; the caller applies to_cache only AFTER its own commit succeeds. Both directions are outages — caching early leaves a closed handle (v2.8.0), never caching makes a sub-db invisible to every later read (v2.8.1). ⚠ THE BIGGEST FIND, and it was not about relations: the v2.10.0 post-replay re-mirror pass ran before index and relation arming, so re-mirrored rows got no index maintenance — the document moved forward in LMDB while its postings did not, so an index-served query returned the row under its OLD value and missed it under the new one. Silently wrong rows on any install with a v2.9 index, relations or not. Now runs after applyIndexDeclarations(). Mirror drift now has a post-READY baseline: one unrepairable row at boot used to permanently refuse every cascade and every CreateRelation for the process's life, on a condition the code treats as advisory — and the error text falsely promised a restart would clear it. Known limits, all deliberate: restrict is checked ONE LEVEL DEEP, so a cascade that would destroy a restrict-protected grandchild is refused rather than recursing; a write extending a TTL during a cascade's fsync-plus-commit still loses (narrow, and only for a cascade/set_null relation whose parent carries a TTL and is renewed after expiry — the fix, if ever needed, is a per-document claim flag, not a versioned delete, which does not close it); an empty-string reference is now a hard rejection where it previously wrote silently; mirror_drift_count_ needs a restart to clear. Surface: CreateRelation/DropRelation/ListRelations/GetRelationInfo/CheckRelation/DescribeDelete (admin-gated; CheckRelation gates before the lookup so a denial is not an existence oracle), client methods (never new struct members — public struct sizes verified byte-identical), CLI relations/relation/relation-create/relation-drop/relation-check/describe-delete/configure-relations, and a create_relation migration op so consumers can declare relations in migration files as they do views. Tests: test_relation_enforcement 370, test_relation_manager 70, test_relation_index 43, test_subdb_identity 264, test_document_ttl 22, test_dual_write_mirror 73; e2e test_relations (two real restarts + a manufactured self-heal), test_relations_client_e2e 33, test_policy_enforcement 34. ctest 23/23.total_matched is part of the contract, and counting matches meant visiting every one; that, not row lookup, is why status="completed" (66% of rows) was declined. (1) Counted plan. For a single unsorted EQ or IN on a non-multivalued index, the total comes from mdb_cursor_count and only the page's rows are read - no selectivity budget applies, so breadth is free. On a production executions (10,118 rows / 592 MB): status=completed limit=10 338ms → 4ms, offset=6000 354ms → 12ms, total 6,689 exact both ways. Page ORDER needs no work: DUPSORT stores a key's ids ascending and document keys are ids, so postings emerge in the order a collection cursor would give. ⚠ A count is only the match count while no row owns more than one posting, so an index records kIndexMultiValuedKey the first time an array value is indexed, and the counted plan declines once set - under an array field a key's duplicate count counts rows CONTAINING the element, while EQ compares the whole array. Set on write, never cleared (clearing would need proof no array remains). (2) Range + sort on the same field. A range walk already emerges in key order, so it IS the sort order: no sorting pass, only the page decoded, total exact because each posting in range is one distinct row. Reversing an ascending walk reproduces sort_documents' reverse-id tie-break exactly. Rows lacking the field need no guard here, unlike pure ordering - a missing value fails a range anyway, so excluding them is correct rather than a silent omission. (3) Distinct values + min/max (GetIndexValues RPC, Client::indexValues, smartbotic-db-cli index-values): one step per distinct VALUE rather than per row, so "which statuses exist" over 10k rows costs four steps. On real data it reports completed 6689 / failed 3410 / cancelled 18 / running 1 - which is also how an operator sees an unselective field coming. ascending=false, limit=1 is the maximum, ascending limit=1 the minimum. The value is read from a row holding it, never decoded from the index key - that keeps the encoding write-only with no decoder to drift from the encoder, and returns the value as stored rather than a reconstruction. An array field reports nothing, because its keys are elements and returning the array would misstate what the key means. (4) Covering reads: investigated and CLOSED as not viable. A read answered from the index alone would still owe the response its metadata - _id, _created_at, _updated_at, _version, _created_by, _updated_by are always retained (verified: projection={_id} returns all six) and only _id is in a posting. It needs an explicit ids-only response mode, which is a contract change, not an optimisation; and the counted plan already cut document reads to the page. (5) ⚠ Unique constraints: built, then deliberately NOT shipped. The check is correct in isolation (find_duplicate_values refuses declaring uniqueness over existing duplicates; enforcement runs inside the document's own transaction) but cannot be turned on: it throws from put(), which runs inside applyDualWriteMirror, and that catches every exception, logs it, bumps mirror drift and flips mirror_healthy_. A rejection would therefore be swallowed - the row still lands in MemoryStore with the constraint unenforced - AND every read in the process would fall back to MemoryStore, which is the v2.8.1 fault exactly. Worse, MemoryStore mutates BEFORE the mirror runs, so a clean rejection needs the in-memory write rolled back. No RPC, config key or client method exposes it, so nothing advertises a constraint that does not hold; the store-level remnant is commented as unreachable and why. Finishing it means propagating UniqueViolation through the mirror without touching health plus rollback, or moving enforcement ahead of the MemoryStore mutation under the same collection lock - both in the write path behind the v2.4.3/v2.4.4/v2.8.0 incidents, so it wants its own change. Also fixed: is_index_meta_key() now excludes BOTH reserved keys from every index walk and count (the multivalued marker joined the v2.4.4 identity sentinel), and rowCountTxn() excludes the sentinel from a collection's row count - a raw mdb_stat includes it, which is what silently disabled the v2.9.2 ordered plan until a test asserted the plan had actually run. Tests: test_subdb_identity 236, index e2e 33, all suites green. Still not served: NE, REGEX, SEARCH, and sort + unselective filter (structural - an exact total requires visiting every match, which is what stopping early avoids).startedAt > p98, 202 rows: 337ms → 9ms). Sorts were not, at all — an index was consulted only to narrow a FILTER, and a Sort is not a filter, so "newest N, unfiltered" walked all 10,118 rows of the 592 MB executions collection to discover what to sort by: 341ms to return one row with the index declared and unused. The control that proves sorting is not inherently unindexed: workflowId=X + the same sort was already 0ms, because a selective filter left one row to order. Fix — orderedHitsFromIndex: walk the sort field's index in key order and stop at offset+limit. 341ms → 0ms, total_matched still exact. Direction handles ties for free: sort_documents breaks an equal-key tie on id ascending / reverse-id descending, and DUPSORT stores a key's ids ascending, so MDB_FIRST+MDB_NEXT and MDB_LAST+MDB_PREV both match without extra work. ⚠ The guard is the whole safety argument. sort_documents returns descending when the LEFT value is missing, so descending places rows LACKING the sort field FIRST — and an index holds no posting for them, so a naive walk would silently omit them from the first page. Wrong rows, not slow ones. Ordering is therefore used only when index entries == row count, i.e. every row has exactly one posting; a sparse field, an unindexable value or an array (several postings) all fail that and scan. A field of one-element arrays would satisfy the count while sort_documents compares whole arrays, so the rows actually fetched are checked and the plan abandoned if any is an array — residual, documented: a row outside the returned page could still differ, and sorting by an array field is not meaningful. Only for unfiltered sorts: with filters, an exact total_matched requires visiting every match, which is exactly what stopping early avoids; the two cannot both hold and the total is part of the contract. ⚠ The bug my own test caught: the first version asserted ordered_scans == 1 for a single query and passed while the plan was never taken — mdb_stat on a collection counts the v2.4.4 identity sentinel, so entries never equalled rows, and all eleven "equivalence" cases were comparing the scan against itself. Fixed with rowCountTxn() (used by the planner's budget too), and the test now asserts the ordered plan ran in all eleven cases. Also added: IN as a UNION of posting lists (per-value counts summed first, so a broad IN is rejected before any list is read) and EXISTS=true as all of a field's postings, which is selective exactly when the field is sparse. EXISTS=false cannot be served — rows without a posting are not enumerable from an index — and a dense field's EXISTS=true is not selective, so both scan. index_plan_stats() grew ordered_scans, union_scans, exists_scans. Tests: 22 more both-ways equivalence cases including descending-with-a-missing-field, one-element arrays, tied sort keys, deep offsets, limit=0, and offset past the end. ctest 20/20, index e2e 33, all suites green. Still not served: NE and REGEX (a full walk either way), SEARCH (whole documents), and sort + unselective filter, which stays a full pass for the exact-total reason above._created_at is ns by default since v2.2.0, well above 2^53). Equality still holds because integral values take the integral branch either way, so 5 and 5.0 are one key. On real production data (executions, 10,118 rows / 592 MB): startedAt > p98 (202 rows, 2%) 337ms → 9ms (37x), identical match count; the same predicate over every row stays 333ms with the index declined. ⚠ The on-disk key format changed, so the sub-db prefix carries a format version — _idx_ → _idx2_. A stale index is therefore never consulted (the new name simply does not exist, the lookup reports "no index", the query scans) rather than misread, which would return wrong rows. applyIndexDeclarations() now self-heals: a declared field whose sub-db is absent is rebuilt at boot with a WARN. Without that, writes would maintain the new index correctly while rows written before the upgrade had no postings, and an indexed query would silently return only the newer ones. Ranges are served only when the index holds ONE type (compare the tag of the first and last key — keys are ordered, so one tag at both ends means one throughout) and that type matches the bound's; across types the scan compares by JSON type order while a walk compares by tag byte, and rather than assume those agree, mixed types scan. ⚠ There is no cheap count for a range, so the walk IS the probe — and on exceeding the budget it returns no-plan, NEVER a truncated list. A partial candidate list would silently drop matching rows, the one failure an index must not have. (2) CONTAINS. An array value now contributes one posting PER ELEMENT (encode_index_keys), which is exactly what CONTAINS asks about (array membership, elements compared with nlohmann ==). Maintenance became a set difference — remove the keys a row no longer owns, add the ones it gained — since a field contributes a set of keys rather than one. Note EQ for a scalar on an array-valued field may now name rows whose array merely contains it; that is safe only because every candidate is re-checked against every filter, so the index narrows work and never decides the answer. EQ for a whole array still has no key and scans. (3) Intersection. When two exact predicates are each too broad alone but narrow together, their posting lists are intersected and used if the result fits the budget. Worth it because postings are ids, not documents: reading two lists costs nothing like the per-candidate decode_document the budget protects against. Correct because each list is a superset of its own predicate's matches, so the intersection is a superset of the rows matching both. (4) CLI: indexes <collection> (reports distinct values and entries, so an operator can see an unselective field coming), index-create, index-drop. Test discipline: 14 more equivalence cases run each query with and without the index and compare ids, order and total_matched; index_plan_stats() grew intersected_scans and range_scans so each new plan is proven TAKEN rather than silently declined — one assertion failed first time on my own bad premise (20 rows of 400 is 5%, which fits the budget alone, so it never needed intersecting; the test now uses deliberately coarse 25%/20% fields). ctest 20/20, index e2e 19 + 14, namespacing 44/44, views + policy + TLS/auth green. Still not served from an index: NE, IN (a union of posting lists, not yet), REGEX, SEARCH, and ranges on mixed-type or non-homogeneous fields._idx_<collection>#<field> sub-db per indexed field, MDB_DUPSORT, key = order-preserving encoded value, data = doc id — DUPSORT gives a value's posting list as a sorted set at no extra structural cost. First use of DUPSORT in the codebase; prime_dbi_cache reopens these with the flag so the handle agrees with how the sub-db was created. Measured on a copy of the live executions (10,089 rows / 505 MB): EQ on workflowId (1 match, 0.01%) 372ms → <1ms; EQ on status="completed" (6,665 matches, 66%) 347ms → 344ms with the index DECLINED. Both identical to the unindexed plan. Declaration is explicit per collection (CreateIndex/DropIndex/ListIndexes RPCs, Client::createIndex/dropIndex/listIndexes), persisted in CollectionCfg inside _collection_meta — an ordinary collection, so WAL'd and snapshotted for free, the versioningEnabled precedent. DatabaseService::applyIndexDeclarations() re-arms them at boot; that step is load-bearing, not bookkeeping — without it a restart leaves an index recorded but unmaintained while the planner still consults it, so queries return stale rows with nothing logged. Three correctness traps, all silent-wrong-data if missed. (1) Index equality must mean what the scan's equality means. The scan's EQ is nlohmann::json::operator==, which compares numbers ACROSS subtypes (json(5) == json(5.0)), so encode_index_key canonicalises integral values to the integer form; otherwise an indexed EQ would miss rows a scan finds. Integers are also NOT routed through double — ns timestamps exceed 2^53 where neighbouring values collide (_created_at is ns by default since v2.2.0). test_secondary_index_keys compares key-equality against scan-EQ over every pair in a corpus (400+ pairs). (2) Maintenance runs in the SAME write transaction as the document, so a write that throws rolls the index back with it; deletes remove the specific id from a value's posting list, not the list. Unindexed collections pay nothing (the write path checks the declaration map and returns). (3) An index must not be able to make a query slower. The guard uses one only while matches are under rows/10, derived from measurement: a full decode_document costs ~8.6× a yyjson parse of the same row (3168ms vs 369ms over the same 193 MB), so an index stops paying above ~11.6% selectivity. Re-decided per query VALUE, not per field, because status="completed" at 66% is exactly the case that regresses. Declaring an index is therefore always safe; using it is the planner's call. The index changes only WHICH rows pass 1 visits — predicate evaluation, sort-key extraction, sorting and pagination are shared verbatim with the scan, and every filter still applies to every candidate, so the index may be a superset: it narrows work, it does not decide the answer. test_indexed_and_unindexed_plans_agree runs 13 query shapes both ways comparing ids, order, total_matched and has_more; index_plan_stats() (indexed / full / declined-unselective) proves the plan was TAKEN rather than silently declined — without it those cases would compare the scan against itself. Fixed on the way: CollectionConfigManager::loadFromStore truncated at 100 — a bare Query, Query::limit defaults to 100. Third occurrence of that trap after ViewManager and PolicyManager. It had to be fixed before index declarations could live there, since a lost declaration is worse than no index. Also index_stats().entries subtracts the v2.4.4 identity sentinel, which is a reserved key and not a posting. Client API is METHODS, not struct members — public struct sizes verified byte-identical against the installed 2.8.1 headers. Limits: only EQ is served; ranges need the integral/non-integral encodings unified (they sit under different type tags, correct for equality but ordering independently); CONTAINS needs one posting per array element; a masked field cannot be indexed and its index is not listed, since an index over unreadable values is an inference channel. Tests: test_secondary_index_keys (32), test_subdb_identity grew to 141, tests/load_test/test_indexes.sh (25 over gRPC including a real restart). ctest 20/20, namespacing 44/44, views + policy + TLS/auth green.mdb_dbi_open - the v2.4.3 handle bug in a FOURTH failure mode, found live while investigating something else. lmdb.h states the rule verbatim: "This function must not be called from multiple concurrent transactions in the same process. A transaction that uses this function must finish (either commit or abort) before any other transaction in the process may use this function." try_open_for_read called it on every read of a collection this process had not yet written, from every gRPC thread at once, inside overlapping read transactions. The v2.8.0 comment there framed the cost as merely "one mdb_dbi_open per read"; it is not slow, it is unsafe. MDB_dbi is an index into the env's shared handle table, and churning that table concurrently silently rebinds handles that committed writes had already cached. Observed live on 2.8.0-3: 41 refusals in 45 minutes, every one caller asked for 'image_hashes' but the handle addresses 'nsfw_images'. The v2.4.4 identity sentinel caught all 41, so nothing was corrupted - but each refusal bumped mirror_drift_count_, and the Find gate (mirrorHealthy() && mirrorDriftCount() == 0) then sent every read in the process to MemoryStore for the rest of its life. Two silent consequences, both live for an unknown period: query.projection stopped working entirely (MemoryStore ignores it - document_store_lmdb.cpp:234), so a paging UI asking for {_id} received every byte; and reads were served by a bounded evicting cache instead of the full dataset. Fix: prime_dbi_cache() opens a handle for every existing sub-db in ONE committed write transaction, and the constructor calls it - not the call site, because a store whose cache was never primed reports every existing-but-unwritten collection as EMPTY, and "the caller must remember to prime" is not an enforcement mechanism. The read path now serves exclusively from the cache and a miss means "no such collection", which is correct because the cache is complete by construction (priming covers what exists, cacheCommittedDbi covers what is created later). After this, only write transactions call mdb_dbi_open, and LMDB permits exactly one at a time - so the contract is satisfied structurally rather than by convention. Logging stays out of document_store_lmdb.cpp (test targets do not link spdlog); the outcome is exposed via primed_count() / prime_error() and reported by ProjectStoreRegistry. Live after upgrade: primed 47 + primed 19 sub-db handles, memoryMatchCount=0, projection back to 166 bytes from 4273, filtered query 408ms. ⚠ Honest test limitation: test_concurrent_reads_do_not_rebind_cached_handles does NOT reproduce the race - reverting the fix leaves it green except for the primed_count assertion, because the torn slot-table update needs an interleaving 8 threads over 10 collections do not reliably hit. It pins the invariant (no read returns another collection's document, no write is refused) and the mechanism; the deterministic evidence is the documented contract plus the production log. test_existing_collection_readable_without_writing_first guards the new risk this fix introduces. Lesson: v2.4.3 fixed read-path caching, v2.4.4 added the sentinel, v2.8.0 stopped caching before commit - all three treated caching as the problem. The actual problem was calling mdb_dbi_open at all outside a serialised write transaction. ctest 19/19.Document for every row in the collection before evaluating the predicate. Measured on a copy of the real smartbotic-automation env (executions, 9800 docs / 505 MB): limit=10 unfiltered 8ms, the same query plus one filter 2463ms. So adding a filter cost 300x, and the browser's filtered views were paying it on every keystroke. Where the time went, measured over 10,124 rows / 193 MB: yyjson parse alone 369ms, parse_to_nlohmann 1947ms, full decode_document 3168ms — materialisation is 88% of the cost, so the ceiling for avoiding it is 8.6x. Fix: a two-pass scan. Pass 1 walks the cursor, parses each value with yyjson only, and evaluates the predicate against that tree through a field resolver — collecting just {id, sort key} per match. It then sorts, and pass 2 does mdb_get + decode_document only for the rows inside the requested page. Result: 2463ms → 402ms (6.1x), and 402ms is essentially the 369ms parse floor, so what is left is irreducible without not-parsing (the "Phase C binary frame"). The comparison logic stayed single-sourced — filter_eval.hpp gained matchesFiltersResolved(resolve, filters) and matchesFilters(doc, filters) became a thin wrapper over it, because two copies of the operator semantics would drift and the divergence would be silent wrong data, not an error. SEARCH is the one exception: it scans the whole document text, so needsWholeDocument(filters) routes any query containing one to the old row-at-a-time path; the resolver-based path returns false for SEARCH (fail closed) so a missed route under-matches rather than over-matches. resolve_from_yyjson must mirror resolveField's mapping exactly — _id/_created_at/_updated_at/_version live at the STORED document's top level as id/createdAt/updatedAt/version, everything else under data, and dotted paths descend objects only. Sort ordering also copies sort_documents' rule for missing keys (ascending puts documents that HAVE the field first, ties broken by id) — verified, not assumed; my first test asserted the opposite and the test was what was wrong. Test: test_filtered_scan_operator_matrix walks all eleven operators plus dotted paths, the four metadata fields, SEARCH, and filtered sort/pagination/total_matched, because a resolver that mishandles one operator returns silently wrong data. (2) Encryption logged plaintext. encryption_manager.cpp:283 logged at INFO on every field encrypt, including the first and last plaintext byte as hex — so sensitiveFields values leaked characteristics into the service log at default verbosity, and did it once per field per write. Now DEBUG, with the byte values gone. On dropping nlohmann entirely (asked, and declined): the hot paths already bypass it — every response goes out through doc_binary::to_json_text (yyjson) and this change removes the last big materialisation — so the remaining 453 references across 65 files are cold paths (config, migrations, policies, views) where nlohmann's exceptions and value semantics are an asset and yyjson's manual-lifetime mutable API would add crash risk to code that runs once at boot. Decisive blocker: nlohmann::json IS the public client API (24 references in client.hpp — insert, get, Filter::value, QueryResult::documents), so removing it breaks every consumer callsite and needs a soname bump. ctest 19/19.LmdbDocumentStore::open_for_write cached the MDB_dbi immediately after mdb_dbi_open, before the caller committed. LMDB keeps a handle private to the opening transaction until it COMMITS and closes it if that transaction aborts — so any write that threw after the handle was cached (a failed mdb_put, a sentinel mismatch, a WriteTxn destructing uncommitted) left a closed handle in the cache, and every later operation on that collection failed EINVAL for the life of the process. Observed in production on 2.7.1, not in a test: find on smartbotic-automation:workflows failed with LMDB cursor_open: Invalid argument on every attempt while every other collection was fine — 6 errors in 12 minutes, workflow listing broken for users, and nothing surfaced it but the service log. Only a restart cleared it (handles live in the env's shared table). This is also the likely cause of the only production SIGSEGV on record: a live PatchDocument → mirrorWriteToDocStore → mdb_put writing through a handle in that state, on the 2.8.0 install. Note the crash is therefore not a 2.8.0 regression — the defect was live on 2.7.1; an upgrade's queued-write burst is just what tends to trip it. Fix: open_for_write no longer caches; callers call cacheCommittedDbi() after wtxn.commit() succeeds. Once committed LMDB promotes the handle into the env's shared table where it stays valid for the env's life — which is what makes caching safe at that point and only at that point. Test: test_aborted_write_does_not_poison_the_collection induces the abort honestly with a key past LMDB's 511-byte limit (MDB_BAD_VALSIZE → throw → abort) and then asserts a later write, scan, count and get on the same collection all still work. Before the fix, three of those failed — including cursor_open, the exact production symptom. Lesson for reviewers: v2.4.3 fixed read-path caching and v2.4.4 added the identity sentinel; neither addressed caching before commit. Any future handle caching needs to answer "what happens if this transaction aborts?"update() was wiping document expiry. (1) The bug. MemoryStore::update and updateIfVersion built a fresh Document from the caller's request; UpdateRequest has no ttl field, so the incoming expiresAt was always 0. Both deliberately carried createdAt/createdBy across from the stored document but not expiresAt — so an update WIPED the expiry and made a TTL'd document permanent. patchDocument() mutates the stored document in place and always preserved it, so the two write paths disagreed and the more commonly used one lost data. It bites where it is least visible: a record written with a TTL and then updated as its status changes (the normal case) silently stopped expiring and accumulated forever — a plausible contributor to executions at 505 MB / 9571 docs. Fixed: an update carries the existing expiry across when the caller supplies none; a non-zero incoming expiresAt still wins, so a TTL can be changed deliberately. There is still no "set TTL only" RPC — ttl_seconds exists on InsertRequest/UpsertRequest/BatchInsertItem but NOT on UpdateRequest/PatchDocumentRequest, so changing a TTL means upserting the whole document. (2) File TTL. FileMetadata.ttl_seconds (relative) is converted once to an absolute FileInfo::expiresAt, so neither a read nor a restart extends a file's life. The sweeper did not exist: Config::cleanupIntervalSec had been there since the beginning and nothing ever read it — no thread, so nothing was ever reclaimed. cleanupLoop() now runs it (condition_variable so shutdown does not wait out an hour), and the loader accepts the plainer cleanup_interval_sec alongside cleanup_orphans_interval_sec. ⚠ Expiry MUST route through deleteFile(), which is what reclaims the BYTES: blobs are content-addressed and deduplicated across projects, so it decrements the refcount and unlinks only on the last reference — unlinking directly would destroy data belonging to a file that has not expired. The first cut broke this in the opposite direction: teaching getFileInfo to hide expired records made deleteFile (which resolved through it) return false for them, so the sweep found records, asked for deletion, was refused, and reclaimed nothing while leaking every blob. deleteFile now uses getFileInfoRaw; deletion has to be able to see what it is deleting. Expired files read as absent immediately, without waiting for the sweep. (3) Per-fileType default retention — storage.files.default_ttl_seconds maps a key to seconds, matched most-specific-first: "<project>:<fileType>", "<fileType>", "<project>:*", "*". The analogue of a collection's defaultTtlSeconds (which is applied on insert/upsert/setAdd/restore). FileMetadata.ttl_seconds is optional and that is load-bearing: absent means "inherit the type default", an explicitly set 0 means never expire and overrides it. A plain uint32 cannot express the difference, which would make opting one file out of a retention policy impossible. Client::uploadFile(data, meta, ttlSeconds) is an OVERLOAD, not a new FileUploadMeta member — see the ABI note below. Tests: tests/test_document_ttl.cpp (9, incl. that preserving must not invent an expiry for a document that never had one) and test_file_project_scope grew to 69, incl. test_expiry_respects_shared_blobs. ctest 18/18, all e2e green.projection as a Client::QueryOptions member. SOVERSION stayed 2, so the already-installed smartbotic-webserver — compiled against the v2.7.0 layout — bound to the new library, read past the end of the struct, and SIGSEGV'd in a restart loop until the packages were rolled back. Client::CollectionConfig (v2.4.5) and FileRecord (v2.6.0) had already changed size under the same soname and got away with it only because nothing restarted at the wrong moment. The rule now: a public struct changing size REQUIRES a soname bump, and "consumers must rebuild" is a changelog note, not an enforcement mechanism. v2.7.1 and v2.8.0 therefore add projection and file TTL as OVERLOADS (find(coll, opts, projection), uploadFile(data, meta, ttlSeconds)), keeping every public struct byte-identical — verified by comparing sizeof against the installed headers AND by running the unchanged webserver binary against the new .so before installing it. Do that check on any release that touches client/include/.anime_images (112 docs / 414 MB, ~2.5 MB of base64 per doc). The app-side diagnosis was right but incomplete: LmdbDocumentStore::scan() decoded EVERY document in the collection, collected them all, then sliced offset..offset+limit. Measured live: find(limit=1) cost 21ms on image_hashes (1005 docs / 0.8 MB) but 382ms on anime_images (112 docs / 414 MB) and 2602ms on executions (9571 docs / 505 MB) — 9x more documents with 500x less data was 18x faster, because it was paying for bytes. Returning one 510-byte document took ~380ms while count() on the same collection took 1ms (it never decodes). Fix: fast path when there are no filters AND no sort — exactly what a paging UI sends. Walk keys with the cursor, decode only the rows inside the window; total_matched comes from mdb_stat so it stays exact without touching a value. Filtered/sorted queries keep the general path since they genuinely need every match. A/B, before→after: anime_images limit=1 319→1ms, limit=10 off=0 298→1ms, executions limit=10 off=0 2655→9ms, off=9000 2516→6ms, sessions 125→1ms. Client::QueryOptions gained projection — FindRequest.projection has existed on the wire since v2.0 and fromProtoQuery always honoured it, but the client never exposed it, so paging a blob collection meant receiving every byte. On the heavy page: full documents 1544ms / 22,791,981 bytes → projection=[_id] 505ms / 1,530 bytes. Where the time actually goes (per 2.91 MB doc, measured, not assumed): decode_document 6.25ms + toProto→to_json_text 4.27ms = 10.5ms to return one document; projection adds 3.45ms. Parsing is NOT the bottleneck — yyjson reads 2.91 MB in 3.5ms (~830 MB/s), so partial/metadata-only decode would save ~4ms of 10.5 and is not worth the complexity. Serialising is what costs, and the response path was already correct: toProto uses doc_binary::to_json_text (yyjson). For reference nlohmann.dump() is 27.5ms vs yyjson_write 2.5ms (11x) on that document — so the one remaining offender, the view projection branch (Get and Find), was swapped to to_json_text. A memcpy of the stored bytes is 0.00ms, which is the real ceiling: not round-tripping at all (store metadata and payload as separate frames so a read hands back payload bytes untouched — the "Phase C binary frame" the source comments anticipate). Worth doing eventually because nothing stops a user putting an image in a JSON field, regardless of file storage existing. Tests: test_scan_fast_path_matches_general_path pins that the fast path agrees with the general one on total_matched, has_more, the final partial page, offset past the end, full coverage when paging, limit=0 (the contract Count depends on), and that a filter or sort still forces the general path. ctest 17/17, namespacing 31/31, views + policy enforcement green.docs/superpowers/specs/2026-08-08-rls-cls-design.md. Before this there was no access control beyond authentication — every key holder had identical, complete access, and views were never a boundary (the guide claimed they were; corrected). Principal = named API key. auth.keys[] entries may be {"name","key"}; a bare string still authenticates as the reserved unnamed; no token is the reserved, grantable anonymous (the default 127.0.0.1 listener has no auth and the CLI rides on it, so local access should be an explicit grant). anonymous/unnamed refused as key names; duplicate names refused (a principal must identify one caller). ⚠ Identity MUST be resolved per call, not from the AuthContext. The first implementation stamped the principal into the gRPC AuthContext; those properties belong to the connection, and gRPC pools channels by target, so three clients with three distinct keys all resolved as ops and every check that should have denied passed. PrincipalResolver now maps token→name from the request's own authorization metadata every call; the processor no longer consumes that header. Policy lives in the global _policies collection, id <project>:<principal>, plus <project>:__security__ for the enable flag and mode — an ordinary collection, so it is WAL'd and snapshotted for free (putting it in CollectionOptions would have needed a new WAL op). Rules grant read/write per collection or file type with "*" fallback (exact match wins), a column mask, and a row predicate AND-merged like a view's where. Safety is structural: enabling is refused without an admin policy, and the last admin of a secured project cannot be removed. mode:"audit" evaluates honestly, logs what it would deny, and allows — the only safe way to arm a live project. Coverage was established by auditing every DatabaseGrpcImpl:: handler, not from a list — the first pass missed Upsert, all three Batch*, all four Set*, and Subscribe (which streams document bodies and, with an empty collections list, means every collection; now filtered per event). Non-obvious surfaces also closed: version history (returns old bodies → bypasses masks), ListCollections/ListViews/ListFiles/GetMemoryStats filter per entry, ListFiles recomputes total_count, GetCollectionInfo gates on name not collection. Filtering on a masked field is refused (else the mask is an inference channel); a write touching a masked field is denied, not silently dropped; a row predicate reports not-found, never "forbidden". System collections are admin-only, and the gate special-cases them: they are global, so routing _policies through the per-project evaluator resolved it to project default (normally unsecured) and let anyone read every project's policies — caught by the e2e the moment the client stopped qualifying _-prefixed names. qualify() no longer qualifies _-prefixed collections (they are global; default:_policies does not exist, so reads silently found nothing while writes succeeded). Client reads now THROW on PERMISSION_DENIED (get/exists/find/findWithMetrics/count) — a denial that looked like "no data" left applications unable to distinguish "not allowed" from "nothing there"; same reasoning as the v2.4.2 silent-empty fix. subscribe() was the last unqualified client call: a bare name matched nothing (events carry the qualified collection, so subscriptions silently never fired) and an empty list meant every collection in every project; named collections are qualified and "everything" sends a <project>:* pattern. An audit of all 41 name-carrying client call sites found no others (createProject/dropProject take project names, uploadFile/listFiles set_name take filenames). Service-wide ops cannot be expressed per project: GetStats/SetReadOnly/Create|DropProject require admin of some secured project, ListProjects filters; the real boundary there is listener separation. HealthCheck/GetReadOnlyStatus deliberately open. Management needs no new RPC: _policies writes through the ordinary document API are intercepted on Insert/Upsert/Delete — they refresh the cache and route __security__ through setSecurity so the lockout guards apply. Upsert was missed at first and the symptom was policies that appeared to store and had no effect. CLI: security, security-set <project> <on|off> [enforce|audit], policies, policy, policy-set, policy-rm. Fixed on the way: auth.required=true with tls.enabled=false only logged a WARN and then gRPC aborted the process on SetAuthMetadataProcessor over insecure credentials; now refused at startup. Tests: tests/test_policy_manager.cpp (54), tests/load_test/test_policy_enforcement.sh (19, three distinct named keys over TLS — the suite that caught the per-connection identity bug, which unit tests structurally cannot). ctest 17/17, namespacing e2e 31/31, views + TLS/auth green.records/ tree of .meta.json files, and no project field on any of the five file RPCs. That made "per-project file policy" a statement with no referent, so scoping had to land before the security work (see docs/superpowers/specs/2026-08-08-rls-cls-design.md). Note the metadata is on-disk JSON under <filesDir>/records/<2-char-prefix>/<id>.meta.json, NOT the _files LMDB collection — easy to assume otherwise. FileInfo::project is persisted there; absent means default, never unknown. project added to FileMetadata, DownloadFileRequest, DeleteFileRequest, GetFileInfoRequest, FileInfo, ListFilesRequest; empty resolves to default. Cross-project isolation: new getFileInfoIn / readFileIn / deleteFileIn overloads compare the record's project and report a mismatch identically to a missing record (nullopt / throw / false → gRPC NOT_FOUND) — the caller must not be able to distinguish "owned by someone else" from "does not exist", since that difference is itself a cross-project oracle. The project-blind getFileInfo/readFile/deleteFile remain for operator use and are commented as such; handlers must never use them. listFiles now takes project as its first, non-optional parameter and filters on it before every other predicate. Dedup leak fixed: blob dedup stays global (the disk saving is real) but StoreResult::deduplicated is now computed from whether the requesting project already references that checksum. Reporting the global hit told project A that project B held those exact bytes — upload a candidate, read the flag, learn whether a peer namespace has the file. getRefCount() stays global and is operator-only. Migration: FileManager::stampMissingProjects() writes project: "default" onto records with no project key, idempotent, called from initialize() after auditSubdbPlacement(); advisory (warns, never fails startup) since a file-metadata stamp is not a reason to refuse service. Records that already declare a project are never restamped, so the migration cannot relocate a file. Client: project is filled from Config::project on all five calls and read back into FileRecord::project; adding that member changes the struct size, so consumers must rebuild (SOVERSION stays 2). Files use a separate project field rather than the project:name string form collections use. Tests: tests/test_file_project_scope.cpp (30 assertions) + tests/load_test/test_client_namespacing.sh grew to 29. ctest 16/16, views e2e + TLS/auth 4/4 green.Client::createCollection, dropCollection and getCollectionInfo sent set_name(name) bare while ~30 other call sites send set_name(qualify(...)). qualify() prepends the project unconditionally, including default, so there was no project where the two paths agreed. One createCollection("things") + one insert("things") from the same client produced two collections: bare things received the options (encrypted, maxVersions, vectorDimension, defaultTtlSeconds) and stayed empty, while <project>:things was created implicitly by the first insert with defaults. Silent — no error anywhere. There is no server-side normalization (MemoryStore::createCollection stores the string verbatim; only LMDB routing calls resolveCollection), so the whole scheme depends on the client qualifying. Consequences, all reproduced: vector_dimension is immutable after creation, so a declared vector collection could never get its dimension and similaritySearch returned 0 hits; encrypted: true silently did not apply to the collection holding the data; and worst, dropCollection returned true while every document remained readable — it dropped the empty phantom. Without a prior createCollection it returned false instead, so the failure mode depended on call history. Same class as the v2.4.2 createView break, second occurrence in the same file. Audit: exactly three methods were wrong; createProject/dropProject (project names) and uploadFile/listFiles (filenames) are correctly bare. listCollections() now unqualify()s results so bare names round-trip; note ListCollectionsRequest still has no project filter, unlike ListViewsRequest, so other projects' names remain visible. Migration: consumers upgrading will find leftover empty phantom collections (harmless litter). Options that were swallowed do NOT retroactively apply — createCollection on a now-correctly-resolved existing collection returns false and only updates maxVersions, so a collection that needed vector_dimension must be recreated. Versioning switch: CollectionCfg::versioningEnabled (default true) turns version history on/off on an existing collection via configureCollection. It lives in CollectionCfg (the _collection_meta system collection), not CollectionOptions, specifically because _collection_meta is an ordinary collection and therefore WAL'd and snapshotted for free — putting it in CollectionOptions would have required a new ALTER_COLLECTION WAL op to survive a restart between snapshots. Enforced in one place, MemoryStore::saveToHistory, so no write path can forget it. Disabling stops NEW versions; existing history stays readable, so it is reversible. NOT the same as maxVersions == 0, which means unlimited. ConfigureCollection is now a partial update: optional bool versioning_enabled (proto3 field presence) and empty timestamp_precision both mean "leave unchanged" — load-bearing, since a plain proto3 bool defaults to false and would have silently disabled versioning on any precision-only call. Client::CollectionConfig::versioningEnabled is std::optional<bool>; adding it changes the struct's size, so consumers must rebuild (SOVERSION stays 2, matching the v2.1 precedent). Test: tests/load_test/test_client_namespacing.{cpp,sh} — 17 assertions over gRPC with a non-default project. This is the boundary both namespacing bugs slipped through: tests/test_views.cpp only unit-tests applyProjection() in-process, and nothing drove a real Client against a real server with Config::project set. ctest 15/15, views e2e + TLS/auth e2e 4/4 green.get image_hashes/<id> → not found, get executions/<id> → readable, insert image_hashes/<id> → "already exists". No id index exists; the three operations simply consult different substrates. Get/Find/Exists are LMDB-first, insert's duplicate check reads MemoryStore (memory_store.cpp:271). MemoryStore was right; LMDB had the document in the wrong sub-db. Root cause is the same stale MDB_dbi v2.4.3 fixed, in its second failure mode. MDB_dbi is an index into the env's shared handle table, not a pointer. Pre-2.4.3, try_open_for_read cached a handle opened inside a ReadTxn; the abort released the slot WITHOUT bumping me_numdbs, so the next mdb_dbi_open for an unrelated collection was handed the same number. Whether you then got EINVAL (v2.4.3's drain incident) or a silently wrong sub-db depended only on whether something had reclaimed the slot. Writes through a reclaimed slot succeed, into a stranger's collection, and nothing detected it: mirror_healthy_ only tracks writes that throw. Damage found: 31 rows in smartbotic-automation — 23 in executions declaring image_hashes, 6 in workflows declaring sessions, 1 in workflows declaring users, 1 in nsfw_temp declaring workflows. default was clean. 29 of the 31 existed ONLY in the wrong sub-db, so a delete-the-strays repair would have destroyed them. The repair oracle is the data itself: each stored document carries its own collection field, so a misfiled row is self-identifying — no cross-referencing MemoryStore or the WAL. Prevention — storage/subdb_identity.{hpp,cpp}: every sub-db carries a reserved key ("\0__subdb_identity__", leading NUL so it cannot collide with a doc id) whose value is the sub-db's own name. open_for_write verifies it on every cached-handle reuse and throws on mismatch; one mdb_get per write buys a loud failure instead of silent cross-collection corruption. count() subtracts it, scan()/scan_vectors() skip it. Absence is treated as "unknown", not "wrong", so pre-2.4.4 sub-dbs keep working and acquire a sentinel on their next write. Detection — DatabaseService::auditSubdbPlacement() runs at boot per project, logs ERROR with a per-pair summary and the exact repair command. Advisory: never blocks startup, since misplacement is an operator-repairable data-location problem, not a reason to refuse service on the rest of the dataset. Repair — storage/subdb_placement.{hpp,cpp}, compiled into both the service and the CLI so there is one implementation: smartbotic-db-cli verify-subdbs --env <path> [--project N] (read-only, safe against a running server, exit 1 if anything is misfiled) and reconcile-subdbs ... --apply (dry run by default; service MUST be stopped). Repair never deletes: a row moves to its declared home only when the home has no row under that id, otherwise the stray copy is parked in _orphans_<subdb> for manual comparison. --stamp-identity is opt-in and requires the server to already be ≥ 2.4.4 — a 2.4.3 binary does not skip the sentinel and would throw decoding it in scan() and miscount by one per collection. Order of operations on an existing box: repair placement → upgrade → stamp. Counts are now LMDB-first too. Count called store_.count() (MemoryStore only) while Get/Find/Exists were LMDB-first, so it under-reported whenever the two diverged — and they diverge routinely, because MemoryStore is a bounded cache that evicts (pressure=soft fires on this dataset at the 512 MB budget) while LMDB is the full dataset. Both Count and GetCollectionInfo now read LMDB behind the same gate; unfiltered via ds->count(), filtered via scan() with limit=0 (total_matched is computed before pagination, so no document is materialised). smartbotic-db-cli count calls GetCollectionInfo, NOT the Count RPC — that is why fixing only Count appeared to change nothing. CollectionInfo::sizeBytes deliberately stays a MemoryStore estimate: it measures resident footprint, which is what the eviction knobs act on. Observed before/after on smartbotic-automation:image_hashes: 47 / 47 / 69 → 70 / 70 / 70.
⚠ NEVER open a second MDB_env on a path this process already has open. The first 2.4.4 build did exactly that — auditSubdbPlacement() called the path-taking audit(), which opens its own env and closes it. LMDB coordinates readers with POSIX record locks, and POSIX locks are per-process, not per-descriptor: closing ANY fd on a file releases every lock the process holds on it. The audit's mdb_env_close() therefore destroyed the lock state of the service's own env, and every subsequent mdb_txn_begin returned EINVAL for the life of the process. All LMDB reads were down for ~90s in production before rollback to 2.4.3. Also across containers (found 2026-10-08): a second process in a DIFFERENT PID namespace (another Docker container sharing the data directory) cannot even read: mdb_txn_begin failed EAGAIN, because LMDB's reader table is keyed by PID and the namespaces disagree. Offline tooling against a containerised server's data stops the server first. Use audit_env(MDB_env*) in-process — it borrows an open env and opens only a read txn. audit(path, ...) is CLI-only (separate process). Test any change to env lifetime against a copy of the real dataset on a staging port before installing — the unit suite does not catch this, because it never has two envs open on one path. Tests: tests/test_subdb_identity.cpp (23 assertions; misbound_handle_is_refused reproduces the misbinding by verifying a handle under the wrong name, test_scan_limit_zero_reports_total pins the filtered-count contract). ctest 15/15. Deployed 2.4.4-1; both projects stamped (44 + 11 sub-dbs).LmdbDocumentStore::try_open_for_read called mdb_dbi_open inside a ReadTxn and cached the handle in dbi_cache_. LMDB keeps a handle private to the opening transaction until it COMMITS and closes it if the transaction ABORTS — and ReadTxn::~ReadTxn always aborts. So the cached MDB_dbi dangled and every later mdb_put/mdb_cursor_open on that collection failed EINVAL for the life of the process. It hit whichever collection was READ before it was WRITTEN after a restart (smartbotic-automation:sessions); peers were fine because open_for_write commits, promoting the handle into the env's shared table. Fix: the read path no longer caches — the handle is valid inside its own txn, which is all the caller needs, and writes still populate the cache permanently. That failed mirror write flipped mirror_healthy_=false, sending all reads to MemoryStore. (2) Eviction drained the store. Eviction assumes estimatedMemoryBytes_ falls as docs leave. It didn't (347→358 MB while evicting 3000 docs; process RSS peaked at 1.9 GB against a 512 MB budget, so the estimator is ~5x low), so current <= targetBytes was never satisfied and it trimmed one chunk per tick for 30 minutes until 5996 of ~5990 docs were gone — into the MemoryStore that reads had just been redirected to. Fix: evictionMaxEpisodePercent (default 50) caps what one pressure episode may evict, enforced per pass (a Hard/Emergency tick runs up to 20 chunks, enough to empty a store between tick-level checks); an episode re-arms only after kEvictionRearmNormalTicks=3 consecutive Normal ticks, since eviction transiently dips the estimate and a per-tick reset drains in 50% stages; plus a no-progress detector that pauses eviction after 3 consecutive evicting ticks that fail to lower the estimate. Both log ERROR — hitting them means the estimator is wrong, not that the store is too big. (3) 104 assertions were no-ops. CMAKE_BUILD_TYPE=Release sets -DNDEBUG, so every assert() in test_views (24), test_snapshot_durability (30), test_timestamp_precision (26), test_config_dropins (14) and test_eviction (10) compiled away — the suites ran, printed PASS, and verified nothing. tests/CMakeLists.txt now applies -UNDEBUG to test targets. Restoring them surfaced no further failures. Tests: test_read_first_collection_survives_repeated_access (reproduces EINVAL — note the ENV must be reopened, not just the store, since handles live in the env's shared table), test_eviction_never_drains_the_store. ctest 14/14, both e2e suites green.default. Client::createView sent name bare but collection qualified (client/src/client.cpp), so ViewManager's cache keyed on the bare name while Find/Get/Count looked up the project-qualified one — the keys could never meet. The miss fell through to "treat it as a real collection", yielding 0 docs and no error. tests/test_views.cpp passed throughout because it only unit-tests applyProjection() in-process; the break lives at the client/server boundary. Fix: views are now keyed by their qualified <project>:<name> form. The client qualifies view names on createView/dropView/getViewInfo and un-qualifies them on the way back (unqualify()), so the caller keeps using bare names and listViews() round-trips. Two projects may each own a view of the same name; previously the global registry rejected the second one as a duplicate. ListViewsRequest gained a project field (additive, field 1) — empty means "all projects" for operator/CLI use, clients always set their own. Migration: legacy bare-named rows in _views are re-keyed into default on load (ViewManager::loadFromStore), idempotent, logged as re-keyed N legacy view(s). Behavior change: Find on a name that is neither a view nor a collection returns gRPC NOT_FOUND, and Client::find/findWithMetrics throw std::runtime_error rather than returning {} — the silent-empty is what hid this bug. Consumers that relied on empty-for-missing must catch (smartbotic-automation's StorageClient::query was patched to convert it to ErrorCode::CollectionNotFound). Test: tests/load_test/test_views_multiproject.sh — 17 checks over both projects, projection, name reuse, cross-project isolation, NOT_FOUND. ctest 14/14, TLS/auth e2e 4/4.--version reports the real version. printVersion() carried a hardcoded "1.0.0" literal, so the server binary misreported itself for the whole 2.x line — --version was useless for triage and only dpkg -l was truthful. SMARTBOTIC_DB_VERSION_STRING is now injected into the service target from the top-level VERSION file (which CMakeLists.txt:7 already read but never passed down). The #ifndef fallback is "unknown", not another literal. BUILD_GIT_COMMIT was declared-but-unused in packaging/Dockerfile.build until v2.8.0 — build.sh computed it and passed it as a --build-arg, and the ARG was declared, but unlike BUILD_VERSION it was never promoted to an ENV, so nothing consumed it and packages recorded no provenance. Fixed in v2.8.0: the Dockerfile promotes it, CMake takes it from the environment (falling back to git rev-parse, then "unknown"), and --version now prints version X.Y.Z (commit abc1234) so two builds of the same version can be told apart.storage.listeners[] config array — each entry has its own bind, port, tls{}, auth{}. One process, multiple grpc::Server instances, same DatabaseGrpcImpl registered on each. Default policy preserves v2.3: 127.0.0.1 plaintext, no auth (the v2.3 bind_address + rpc_port keys are synthesised into one listener when listeners[] is absent). New listeners (LAN/public) are opt-in. TLS: tls.enabled + tls.cert_path/tls.key_path. If missing AND tls.auto_self_signed_if_missing: true (default), a 10-year RSA-2048 self-signed cert is generated at <dataDir>/tls/auto_self_signed.{pem,key} on first boot (SubjectAltName includes DNS:localhost, IP:127.0.0.1, plus the bind as DNS-or-IP). Operators with real PKI override by dropping their cert at cert_path. Loud WARN on auto-generation. Auth: auth.required + auth.keys[]. Server attaches BearerAuthProcessor (service/src/auth/auth_interceptor.{hpp,cpp}) via SetAuthMetadataProcessor — constant-time compares authorization: Bearer <key> against auth.keys[]. gRPC handles UNAUTHENTICATED rejection without per-handler code. Refuses to start if auth.required=true with empty keys; logs WARN if auth required without TLS. Client: Client::Config::{tls_enabled, tls_ca_cert_path, tls_insecure_skip_verify, auth_token}; auth attached via ClientContext::AddMetadata in setDeadline() so every RPC (unary, stream, file) is covered. tls_insecure_skip_verify (dev-only) uses grpc::experimental::TlsChannelCredentialsOptions + NoOpCertificateVerifier; loud WARN on every connect. CLI: smartbotic-db-cli generate-auth-key (32 random bytes → base64) and generate-tls-cert --bind <addr> [--out-cert PATH] [--out-key PATH] [--days N] (offline cert minting via OpenSSL 3 EVP API). End-to-end test: tests/load_test/test_v24_tls_auth.sh boots a server with both plaintext + TLS+auth listeners, drives the new client through 4 scenarios — plaintext-local OK, TLS+token OK, TLS+wrong-token UNAUTHENTICATED, TLS+no-token UNAUTHENTICATED. All 4 pass. ctest 14/14 green.MemoryStore::getEvictionCandidates compared doc.updatedAt against a millisecond-scaled hotWriteFloor; v2.2.0's default-precision flip to nanoseconds made every doc look "always within the hot-write window" so eviction never fired. Pre-existing v2.2.0 regression — load_test_mixed was never re-run after v2.2.0 shipped. Fix: pick ms- or ns-scaled floor per-doc using the 10^15 magnitude heuristic. (2) DatabaseService::applyReplicatedEntry called MemoryStore::loadDocument which bypasses the persist callback, so the v2.3 LMDB mirror never fired for replicated entries. Followers got writes into MemoryStore but the LMDB env stayed empty; v2.3 LMDB-first reads on the follower returned 0 docs. Fix: explicitly drive applyDualWriteMirror through the project registry after loadDocument. Replication catch-up time on a 100-doc test: 65ms.project namespaces, each with its own collections. Wire form: <project>:<collection> (e.g. my_app:users); bare names like "users" auto-qualify to "default:users" so every v2.0-v2.2 client keeps working without code changes. Storage: one LMDB env per project at <dataDir>/projects/<name>/env/. On first v2.3 boot the legacy <dataDir>/env/ is atomically renamed under projects/default/env/ (idempotent; refuses to start if both exist). Server-side: ProjectStoreRegistry (service/src/storage/project_store.{hpp,cpp}) owns the per-project envs; DatabaseService::docStore(project) resolves the LMDB store for a given name; mirror routing is via a resolver callback the service hands to MemoryStore::setDocumentStoreMirror(resolver, ...). Client-side: Client::Config::project defaults to "default"; every outgoing collection name is auto-prepended (qualify(coll)) unless it already contains :. Per-call overrides via the qualified form always win. New gRPC RPCs: ListProjects, CreateProject(name), DropProject(name) — default cannot be dropped. CRUD is idempotent and validated against ^[a-zA-Z_][a-zA-Z0-9_-]{0,62}$ (no :, no /, no _-prefix). Reserved:default(always present);_-prefix(system). Tests:test_project_addressing(23 parser assertions),test_project_crud` (29 placeholder assertions). 14/14 ctest green. Stress: load_test_mixed still passes against the multi-project build.MemoryStore::updateIfVersion was missing extractVector + storeVector + mirrorVectorToDocStore calls — optimistic-lock updates on vector collections left the vector mirror stale, so SimilaritySearch returned old vector scores while Get returned new doc bodies; (2) DatabaseService::backfillIntoDocStore walked every doc into LMDB but never set _meta.schema_version=2, so every boot re-backfilled the entire dataset (Zoe-scale ~1.85M docs = minutes of pre-READY blocking on every restart); (3) SimilaritySearch LMDB handler returned INTERNAL instead of INVALID_ARGUMENT when an unrelated throw (e.g. bad_alloc) fired after a dimension-mismatch was already observed in the scan. Exposes smartbotic::db::storage::mark_migration_complete(env) for the backfill marker. Tests 12/12 green."ns". BREAKING for fresh collections. CollectionCfg::timestampPrecision default went from "ms" to "ns" so rapid-write collections (chat messages, metrics events, tool-call audits) get nanosecond stamps and strict ordering without needing an explicit configureCollection() call. Closes shadowman audit B5. Operators who need ms can still set it explicitly. Existing collections that already have a stored config record keep their value — only collections created post-upgrade WITHOUT an explicit configureCollection() inherit the new default. Mixed-precision rows in the same collection are read-correct via the 10^15 magnitude auto-detect; operators wanting clean rows should run migrateCollectionTimestamps. update() docstring updated to clarify: it OVERWRITES the doc; use patch() for partial mutations. Reflects shadowman audit B6.catch → fall back to MemoryStore paths in Exists / Get / Find / SimilaritySearch. A live LMDB exception now returns gRPC INTERNAL to the client instead of silently being masked by MemoryStore. The gate-closed fallback (mirror_healthy_=false, system collection, env unopened) stays — that's correctness, since MemoryStore can legitimately be ahead of LMDB when a mirror write has failed. Answers shadowman audit F3: usedWalFallback / walMatchCount / memoryMatchCount / memorySearchMicros / walSearchMicros are guaranteed zero on the LMDB-served path. Any non-zero value is a real signal — it means the read fell back to MemoryStore (mirror unhealthy). Operators can treat walMatchCount > 0 as a paging/SLA alert.smartbotic-database-migrate-v1 deb in v2.5 once every production host has booted v2.4 ≥ once. v2.x is the project's terminal arc, no v3 planned. F2 — setReadOnly / lock() / unlock() are dual-audience: operator-side via smartbotic-db-cli unlock and client-side via Client::lock() for self-defensive migrations. F3 — see above. F4 — migrateCollectionTimestamps cost benchmark deferred until shadowman starts D.1 (we haven't seen real traffic on the path yet); back-of-envelope ~1ms per 1k docs on Zoe-shape data, online-safe up to ~1M docs.smartbotic::database::QueryOptions struct from client/include/smartbotic/database/document.hpp (dead code; the EQ-only vector<pair<string, json>> shape that predated FilterOp). Removed the no-options Client::find(collection) overload — pass QueryOptions{} explicitly. Added ergonomic factories on Client::Filter: Filter::eq / ne / gt / gte / lt / lte / in / contains / exists / regex / search. Callsites now read like the predicate they're asking: find("users", {.filters = {Filter::gt("age", 18), Filter::in("role", {"admin", "owner"})}}). SOVERSION stays at 2 (matches the v2.0.0 deb; no soname bump needed) — consumers must rebuild against v2.1 headers, but the soname is identical. libsmartbotic-db-client (>= 2.1.0) should be the floor in consumer deb deps.<dataDir>/env/. Each user collection becomes one sub-db <collection> for documents; collections with vector_dimension > 0 get a sidecar _vectors_<collection> storing raw float32 bytes keyed by docId. LmdbEnv (RAII over MDB_env*) is opened in DatabaseService::setupComponents(); LmdbDocumentStore provides put/get/del/scan + put_vector/del_vector/get_vector. Dual-write mirror runs under MemoryStore's per-collection lock (mirrorWriteToDocStore + mirrorVectorToDocStore invoked before lock.unlock() at every write site), so concurrent LMDB readers observe the same state as MemoryStore readers — no race window. On failure: ERROR log, mirror_drift_count_ bumps, mirror_healthy_ flips to false; read handlers (Exists/Get/Find) fall back to MemoryStore. Filter eval lifted to service/src/storage/filter_eval.hpp shared between substrates so divergence is attributable to data state, not code paths. v2.0 read coverage: Exists, Get, Find, SimilaritySearch all LMDB-first when mirror_healthy_ + zero drift. SimilaritySearch iterates the _vectors_<collection> sub-db via DocumentStore::scan_vectors and scores with the AVX2/SSE4.1/scalar SIMD kernel extracted to service/src/storage/cosine_simd.hpp. Deferred to v2.1: history (_history_<coll>) / files (_files) / views (_views) sub-db migration, MemoryStore decommission, write-handler migration so handlers call doc_store_->put() directly. Migration: v1.x→v2.0 auto-migrates on boot (--migrate-from-v1 opt-in / --no-auto-migrate opt-out) via migrate_v1_to_v2; backfill of any docs added before mirror wiring runs sync in initialize(). Eviction config knobs (max_memory_mb, eviction_chunk_size, etc.) are kept for back-compat with v1.x snapshots-still-loaded-into-MemoryStore but emit a deprecation WARN at boot (that WARN said "removed in v2.1"; they never were, they remain the live MemoryStore budget, eviction and write-admission controls, and the WARN was removed after 2.21.2 because it invited operators to delete the budget). RSS is bounded by the LMDB mapsize + OS page cache, not by MemoryStore eviction. Stress numbers (load_test_mixed 30s / 4 writers / 8 readers / 32MB MemoryStore budget): 2385 writes/s, 5769 reads/s, p99 < 100ms, 0 hard failures, 240k ops total, 282MB persisted in LMDB. New runtime dep: liblmdb0.Canonical source for all smartbotic-database Debian packages.
Replaces the old shadowman-database and callerai-storage packages.
# Production (Docker, Debian 13)
./packaging/build.sh # Build 4 .debs
./packaging/build.sh --rebuild-base # Rebuild Docker base image
./packaging/build.sh --sync --suite trixie # Build + publish to repository.smartbotics.ai
# needs a smartbotics-deb-repo checkout: next to
# this one, or wherever $DEB_REPO_DIR points
# Local development (native, current system)
./packaging/build.sh --local # Build 4 .debs
./packaging/build.sh --local --install # Build + install locally
./packaging/build.sh --local --no-package # Build only, no .debs
./packaging/dev.sh build # The same build, inside the Debian 13 image
# One-sided release (2.15.0+): build all four, publish only one side
./packaging/build.sh --sync --suite trixie --only client # lib, -dev, cli
./packaging/build.sh --sync --suite trixie --only server # smartbotic-database
./packaging/compat.sh 2.14.0 # this tree vs a RELEASED version, both ways
| Package | Contents | Deployed where |
|---|---|---|
smartbotic-database |
Server binary + systemd + config | Production DB servers |
libsmartbotic-db-client |
Shared .so (runtime) |
All production machines |
libsmartbotic-db-client-dev |
Headers + linker symlink + .proto + cmake config |
Docker build images, dev workstations |
smartbotic-db-cli |
CLI tool | Anywhere (optional) |
After ./packaging/build.sh --local --install, consumer projects can use:
find_package(smartbotic-db-client REQUIRED)
target_link_libraries(myapp PRIVATE smartbotic::db-client)
The submodule fallback still works for projects that haven't switched (BUILD_SHARED_LIBS=OFF).
| Project | Depends on | Min version | Migrations dir |
|---|---|---|---|
| shadowman-cpp | smartbotic-database (>= 1.2.0) |
1.2.0 | /opt/shadowman/share/shadowman/migrations/json |
| callerai | smartbotic-database (>= 1.2.0) |
1.2.0 | /etc/callerai/migrations |
One release a week, on Tuesday. Changes merge to main continuously; a
release is cut on Tuesday from whatever main holds. 2.12.0-2.19.0 were
sixteen releases in nine days, one per consumer request - each a tag, an apt
publish, a container restart and a round of consumer warnings. Not again.
## Unreleased in CHANGELOG.md in the
same commit. Cutting a release renames that heading to ## X.Y.Z - date; the
Gogs release notes are that section.VERSION is bumped only when cutting the release, never per change or per
branch. All features merged that week fold into one minor bump, fixes into the
patch level../packaging/build.sh (no --sync)
builds the four packages from main into dist/debian13/; a consumer installs
those into a throwaway Debian 13 container to build and test against the new
feature. Never published to apt, never deployed. No testing suite or branch.dev.sh e2e all, compat.sh against the
last two released versions), symbols/update.sh, rename the changelog
section, signed tag, build.sh --sync --suite trixie, Gogs release from the
changelog, container upgrade, one consumer notice listing observable changes
(error shapes AND latency), each marked [server], [client] or
[both] - a server-side change reaches every consumer at the restart with
no client bump (they check their code), a client-side one only when they
rebuild against the new library (they arm a probe), and a consumer pinned to
an old client (smartbotic builds against 2.13.1, which has no
serverSupports) cannot detect capabilities at all.Bump VERSION for API/protocol changes. Deb revision (-N) for packaging-only changes.
Library symbols file (2.18.1-2+). packaging/deb/symbols/libsmartbotic-db-client.symbols
records every symbol the library exports with the first version that shipped it
(bootstrapped by bootstrap.sh from the released libraries in the apt pool,
floor 2.8.0 - soname 2 changed struct layouts up to 2.6.0). create-debs.sh
installs it in the library package with dpkg-gensymbols -c1 (a lost PUBLIC
symbol fails the build: an ABI break under soname 2) and computes the CLI's
Depends with dpkg-shlibdeps - the CLI stays dynamically linked on purpose (a
second, independent user of the library on every host) but no longer pins it to
its own version. When a release adds client symbols: bump VERSION, build,
run packaging/deb/symbols/update.sh build/client/libsmartbotic-db-client.so.<VERSION>
and commit the file; build.sh --sync refuses to publish the library while the
file is out of date (update.sh --check). Symbols outside
smartbotic::database:: (and ::Impl members) are (optional): internals and
template instances may come and go without failing the build.
One-sided releases (2.15.0+). The server and client packages have no
dependency on each other, so a change confined to one side is released with
--only client or --only server: VERSION is bumped as usual and only that
side's packages are published, so e.g. the client may be 2.15.2 while the server
stays 2.15.1. Before publishing, run packaging/compat.sh <the other side's
released version> - that is the combination every host will run. Rules that
keep it safe: the server is additive only (new fields, new RPCs; a meaning never
changes without a new capability name); a client feature that needs something a
2.15.0+ server introduced checks requireCapability() before sending; the two
capability lists (service/src/server_capabilities.hpp,
Client::Capability) change together.
The service uses Type=notify in its systemd unit and signals readiness
via sd_notify(READY=1) only after recovery + migrations complete and the
gRPC listener is up (see service/src/main.cpp around the service.start()
call). This is the lifecycle contract for dependents:
After=smartbotic-database.service + Type=notify on this unit means
systemd blocks the dependent's startup until the DB sends READY=1. A
dependent doing db.get(...) immediately on launch sees a fully-recovered
DB, never an in-recovery one. Pre-1.7.5 the unit was Type=simple, so
sd_notify was decoration and consumers could observe an in-recovery DB
and silently fall back to defaults — surfaced on the shadowman side as
instance_type reading null and Dev mode enabled never logging until
manual restart.TimeoutStartSec=300 covers slow recoveries on large datasets. The
service emits EXTEND_TIMEOUT_USEC=600000000 (10 min) at each phase
boundary as belt-and-braces against systemd's start watchdog.STATUS=... notifications are emitted at each phase ("Initializing —
running recovery and migrations" → "Starting gRPC server" → "Ready") so
systemctl status smartbotic-database shows where the service is during
a slow boot.sd_notify(STOPPING=1) is emitted on graceful shutdown so dependents
observe a draining state distinct from a crash. The graceful-shutdown
path also takes a final snapshot (v1.8.0 hardening) so the next boot's
recovery is TrivialSuccess rather than WalOnlyReplay.Dependents (shadowman-* services and any other consumer) should:
After=smartbotic-database.service and Wants=smartbotic-database.service.Type=notify if they have a meaningful "ready" boundary.Operator-facing tooling (deb postinst, ansible, etc.) should not layer
its own port-poll or sleep loops on top of the unit. systemctl restart
smartbotic-database (or systemctl start ... && systemctl start dependent)
already blocks correctly until READY.