integration-guide.md 139 KB

Smartbotic Database Integration Guide

How to install, configure, and integrate smartbotic-database into your C++ project.

Table of Contents


Release cadence

New versions are published to apt once a week, on Tuesday (CHANGELOG.md lists what each contains; ## Unreleased is what the next Tuesday brings). Out-of-cycle releases happen only for security fixes, data loss and regressions of the latest release.

Need a feature before Tuesday? It is on main as soon as it merges. Build the packages yourself and test in a throwaway container - nothing is published:

./packaging/build.sh                     # -> dist/debian13/*.deb (no --sync: not published)
docker run --rm -it -v "$PWD/dist/debian13:/debs:ro" debian:trixie bash
#   apt-get update && apt-get install -y /debs/libsmartbotic-db-client_*.deb ...

Production takes the feature from apt on the next Tuesday.

Installing the Database

From APT Repository

Add the Smartbotics repository to your system:

# Download GPG key
curl -fsSL https://repository.smartbotics.ai/smartbotics-repo.gpg | \
    sudo gpg --dearmor -o /usr/share/keyrings/smartbotics-repo.gpg

# Configure authentication
sudo tee /etc/apt/auth.conf.d/smartbotics.conf << EOF
machine repository.smartbotics.ai
login callerai
password <repo-password>
EOF
sudo chmod 600 /etc/apt/auth.conf.d/smartbotics.conf

# Add repository
echo "deb [signed-by=/usr/share/keyrings/smartbotics-repo.gpg] https://repository.smartbotics.ai trixie main" | \
    sudo tee /etc/apt/sources.list.d/smartbotics.list

# Install
sudo apt update
sudo apt install smartbotic-database

This installs:

  • /usr/bin/smartbotic-database — the server binary
  • /etc/smartbotic-database/config.json — configuration file
  • smartbotic-database.service — systemd service (starts automatically)

The service listens on localhost:9004 by default.

Verify Installation

# Check service status
sudo systemctl status smartbotic-database

# Check health via CLI (if installed)
smartbotic-db-cli health

Available Packages

Package What it provides Install when...
smartbotic-database Server + systemd service You need to run the database on this machine
libsmartbotic-db-client Shared library (.so) Your application links the client at runtime
libsmartbotic-db-client-dev Headers + cmake config You're building a C++ project against the client API
smartbotic-db-cli CLI admin tool You want to administer the database from the command line

Installing the Client Library

On a Development Machine (for local builds)

sudo apt install libsmartbotic-db-client-dev

This pulls in libsmartbotic-db-client (the runtime .so) as a dependency, plus all development headers needed to compile.

On a Production Machine (runtime only)

sudo apt install libsmartbotic-db-client

Only the shared library — no headers, no cmake config, no dev tooling.


Integrating into a C++ Project

Option A: System-installed package (recommended for Docker builds)

If libsmartbotic-db-client-dev is installed (e.g., in your Docker build image):

# CMakeLists.txt
find_package(smartbotic-db-client REQUIRED)

add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE smartbotic::db-client)

The smartbotic::db-client target automatically sets up include paths and links the shared library.

Option B: Git submodule (for local development on non-Debian systems)

git submodule add ssh://git@git.smartbotics.ai:10022/fszontagh/smartbotic-database.git \
    external/smartbotic-database
# CMakeLists.txt
add_subdirectory(external/smartbotic-database)

add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE smartbotic-db-client)

When built as a submodule, the library is static (.a) and linked directly into your binary.

Option C: Both (recommended)

Use the system package when available, fall back to submodule:

# Try system-installed first (Docker builds, CI)
find_package(smartbotic-db-client QUIET)
if(smartbotic-db-client_FOUND)
    message(STATUS "Using system smartbotic-db-client")
    set(DB_CLIENT_TARGET smartbotic::db-client)
else()
    # Fall back to submodule (local development)
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/external/smartbotic-database/CMakeLists.txt")
        add_subdirectory(external/smartbotic-database)
        set(DB_CLIENT_TARGET smartbotic-db-client)
    else()
        message(FATAL_ERROR
            "smartbotic-database not found. Either:\n"
            "  apt install libsmartbotic-db-client-dev\n"
            "  git submodule update --init external/smartbotic-database")
    endif()
endif()

add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE ${DB_CLIENT_TARGET})

Client API Reference

Connecting

#include <smartbotic/database/client.hpp>

smartbotic::database::Client::Config config;
config.address = "localhost:9004";   // gRPC endpoint
config.timeoutMs = 5000;            // per-RPC timeout
config.maxRetries = 3;              // auto-retry on transient failures

smartbotic::database::Client db(config);
if (!db.connect()) {
    // handle connection failure
}

Mixed versions: what the server supports (2.15.0+)

From 2.15.0 the client library and the server are released independently: a host may run a newer client against an older server, or the reverse. The client can ask the server what it is:

using Cap = smartbotic::database::Client::Capability;
if (auto si = db.serverInfo()) {
    // si->version, si->commit, si->capabilities
}
if (db.serverSupports(Cap::kFilteredSimilarity)) { /* ... */ }
  • Gate on feature NAMES (Client::Capability), not version numbers. A patched or backported server reports exactly what it has.
  • serverInfo() is nullopt for a server older than 2.15.0 (it has no GetServerInfo): such a server has none of the features introduced in 2.15.0 or later. It throws when the server cannot be asked - an outage is not "an old server". The answer is cached for 60 s per Client; serverInfo(true) asks now.
  • The library checks for you. A client method that needs a feature introduced in 2.15.0 or later checks the server first and throws Client::FailedPrecondition, reason server_unsupported, instead of sending a request an older server would misread. Features from before 2.15.0 keep their own guards (for example similaritySearch with filters: filters_unsupported).
  • Every call carries the library's version in the sbdb-client-version metadata, so a server can keep an old behaviour for an old client if a meaning ever has to change. The server is additive-only otherwise: new fields and new RPCs, never a changed meaning without a new feature name.
  • smartbotic-db-cli server-info prints the same answer.

Packaging: smartbotic-database (server) and libsmartbotic-db-client (+ -dev, smartbotic-db-cli) no longer depend on each other, so upgrading one side leaves the other's installed version alone. Up to 2.14.0 the server package pinned the client library to its exact version, so on a host running the server the two always moved together.

Document Operations

// Insert
nlohmann::json doc = {{"name", "Alice"}, {"email", "alice@example.com"}};
std::string id = db.insert("users", doc);
// Or with explicit ID:
std::string id = db.insert("users", doc, "user-123");

// Get
auto result = db.get("users", "user-123");
if (result) {
    std::cout << (*result)["name"] << std::endl;
}

// Update (full document replacement, with automatic optimistic locking)
db.update("users", "user-123", {{"name", "Alice Smith"}, {"email", "alice@example.com"}});

// Update with explicit optimistic locking (fails if version changed)
db.updateIfVersion("users", "user-123", {{"name", "Alice"}}, /*expectedVersion=*/2);

// Patch — atomic partial update (only specified fields are modified)
uint64_t newVer = db.patch("users", "user-123", {{"name", "Alice Smith"}});

// Upsert (insert or update)
auto [uid, isNew] = db.upsert("users", doc, "user-123");

// Delete
db.remove("users", "user-123");

// Check existence
bool found = db.exists("users", "user-123");

Error handling: caller fault or server fault (2.11.4+)

The server classifies every failure with a gRPC status code. From 2.11.4 the client carries that code out to you, so a duplicate key and a broken server no longer look the same. Nothing here needs matching on message text.

Condition Code
A unique constraint is already held by another document AlreadyExists
A child references a parent that does not exist (validate_on_write) FailedPrecondition
A delete is blocked by a relation with on_delete="restrict" FailedPrecondition
The access policy denied the call PermissionDenied
Unknown collection or view on find NotFound
Server unreachable, or the deadline passed Unavailable, DeadlineExceeded

The client has two kinds of call, and each reports the code its own way.

Calls that throw - insert, upsert, similaritySearch, the file calls, and from 2.12.4 every read (see below) - throw Client::Error, which carries code(). Client::AlreadyExists, Client::FailedPrecondition and Client::PermissionDenied are subtypes for when you only care about one:

using smartbotic::database::Client;

try {
    db.insert("users", {{"email", "a@example.com"}});
} catch (const Client::AlreadyExists& e) {
    return conflict(e.what());              // 409: the caller sent a duplicate
} catch (const Client::FailedPrecondition& e) {
    return unprocessable(e.what());         // 422: a referenced parent is missing
} catch (const Client::Error& e) {
    switch (e.code()) {
        case Client::ErrorCode::Unavailable:
        case Client::ErrorCode::DeadlineExceeded:
            return unavailable(e.what());   // 503: worth retrying
        default:
            return internal(e.what());      // 500
    }
}

Client::Error derives from std::runtime_error and what() is the same text as before, so existing catch (const std::runtime_error&) and catch (const std::exception&) blocks keep working untouched.

Calls that report through their return value - update, updateIfVersion, patch, patchWithTtl and remove return false or 0 and do not throw. Each has an overload taking a Client::Failure&:

Client::Failure why;
if (db.patch("users", "user-123", {{"email", "a@example.com"}}, why) == 0) {
    if (why.code == Client::ErrorCode::AlreadyExists) return conflict(why.message);
    return internal(why.message);
}

if (!db.remove("workflows", "wf-1", why)) {
    if (why.code == Client::ErrorCode::Ok) return notFound();     // nothing to delete
    if (why.code == Client::ErrorCode::FailedPrecondition) return conflict(why.message);
}

Failure is reset at the start of every call, so it is safe to reuse.

A failed read throws; "not there" is an answer (2.12.4+)

Before 2.12.4 most reads answered a failed call with the same value they use for "nothing there": get returned nullopt, exists false, count 0, find and every list an empty vector, getCollectionConfig the defaults. An unreachable database or a missed deadline was therefore indistinguishable from a genuine absence, and a transient blip reached an end user as a definite 404 - which a careful client cannot retry, since retrying every 404 retries every real absence too.

From 2.12.4 those reads throw Client::Error on any failed status, with the code (Unavailable, DeadlineExceeded, InvalidArgument, ...), and keep returning the empty value only for a real absence, which the server always reports inside a successful reply:

get, exists, find, findWithMetrics, count, setMembers, setIsMember, getVersionHistory, getDocumentVersion, listCollections, getCollectionInfo, listProjects, getCollectionConfig, hasCollectionConfig, listIndexes, listCompositeUniqueIndexes, indexValues, listViews, getViewInfo, listRelations, getRelationInfo.

try {
    auto doc = db.get("sources", id);
    if (!doc) return notFound();            // the database answered: no such document
    return ok(*doc);
} catch (const Client::Error& e) {
    if (e.code() == Client::ErrorCode::Unavailable ||
        e.code() == Client::ErrorCode::DeadlineExceeded)
        return unavailable(e.what());       // 503: retry; this is NOT an absence
    return internal(e.what());
}

The same applies to a refusal: with an access policy enabled, a read the caller may not make (for example listRelations by a non-admin) throws Client::PermissionDenied instead of answering empty.

Unchanged on purpose: healthCheck() answers false (its job is to say "unreachable"), getHealthInfo()/getStats() return nullopt, getRelationsEnforced() fails toward true, tryGetRelationsEnforced() declines with nullopt, and writes keep reporting through their return value. update() reads before it writes; an outage there used to come back as NotFound ("document not found"), and now comes back with the real code in its Failure.

⚠ Migrating to 2.12.4. A read that returned empty during an outage now throws. Code that called these reads without a try - in particular on a background thread, where an uncaught exception terminates the process - must catch Client::Error (or std::exception). The soname is unchanged, so this applies as soon as the library is upgraded, without a rebuild.

Where the catch actually has to be - found by a consumer auditing for this release, each one a real bug it already had:

  • The adapter, not the call site. A wrapper that turns client calls into a Result must catch Client::Error itself, or every caller behind it inherits the throw. And it must not catch too broadly: a wrapper that caught std::exception and answered "collection not found" for all of them turned an outage into a definite 404 one layer up - the exact bug this release fixes. Treat only code() == NotFound (or a nullopt / empty answer) as absence.
  • A read used as a yes/no test. if (!db.getCollectionInfo(name)) or .ok() inside a loop deciding "does this exist / is this mine" drops a row on a single timeout, even when the outer function is guarded. Only a definite answer may mean "no".
  • Worker threads. An exception leaving a std::thread calls std::terminate. A retention sweep or scheduler that calls the client with no handler anywhere on its thread takes the whole process down on one blip.
  • The file calls have always thrown (uploadFile, downloadFile, getFileInfo, listFiles), so an audit prompted by 2.12.4 can miss them.
  • getCollectionConfig() before 2.12.4 answered the DEFAULTS on failure - an outage read as "versioning disabled" on a collection that has it on. It throws now; code that compared its answer against defaults should be re-checked.
  • deleteFile() / setFileTtl() answer a bare false for "no such file" and for a failed call alike. Since 2.13.0 their Failure& overloads say which: NotFound when the file is not there, the real code when the call failed.
  • Event handlers. Before 2.13.0 a subscribeEvents() handler that threw (or an event body that did not parse) terminated the process from the reader thread. 2.13.0 logs and drops that one event and keeps the stream; a handler should still catch its own errors, since a dropped event is lost.

A write that times out may have happened (2.13.1+)

A DeadlineExceeded on a write does not mean "the write failed": the deadline can expire while the server finishes it. Since 2.13.1 such a failure carries reason outcome_unknown (Failure/FailureDetail, or errorDetail(e) for insert/upsert), and the client only retries a write after a timeout when repeating it cannot change or misreport the result:

Write Retried after DeadlineExceeded?
patch (no increments, no expected version), upsert with an id yes - idempotent
insert, upsert without an id, increment, patchIfVersion, updateIfVersion, remove/removeAs/removeManyAs no - a repeat would duplicate a row, count twice, or report a false AlreadyExists / version conflict / not-found
update() its inner write is not retried (outcome_unknown); a timeout on its READ, before the write is sent, has NO outcome_unknown and is safe to repeat

The reason is set wherever the failure is reported: on the thrown error (errorDetail(e)) for insert/upsert, and on the Failure/FailureDetail out-parameter for patch, increment, updateIfVersion, update, remove/ removeAs and removeManyAs. update() reads before it writes: a timeout on that read means the write was never sent, so it is DeadlineExceeded WITHOUT outcome_unknown - the outcome is known, nothing happened.

Adopting the reason means auditing EVERY write call. The out-parameter overloads have existed since 2.11.4/2.12.0, and a consumer that adopted them for the calls with obvious structured fields (remove's relation, increment) but left update/patch/patchWithTtl on the bare bool/version forms sees no outcome_unknown from its most common writes - that is how smartbotic found it.

Unavailable and ResourceExhausted are still retried: the server did not act. Do not map DeadlineExceeded on a write to "retry as-is". With outcome_unknown, read the row first (or write under a fixed id) and decide. Large writes also get a longer deadline: timeoutMs plus one second per 4 MiB.

update() re-reads and retries only on a version conflict; before 2.13.1 it retried every refusal (read-only, memory pressure, size) and then logged "version conflicts".

A row must stay readable (2.13.1+)

A write that would store a document no read could send back is refused with InvalidArgument, reason document_too_large: an insert/update/upsert/ batch body, or the RESULT of a patch. The limit is the server's max_send_message_size_mb less 256 KB. Before 2.13.1 a row could grow past it one small patch at a time and then fail every get with message_too_large. Rows already that large stay unreadable; the export names them row_too_large.

connect() actually connects (2.13.1+)

connect() waits up to timeoutMs for the channel to connect and returns false when the server cannot be reached. Before 2.13.1 it returned true without opening anything, even against a dead port. On false the client is still usable (gRPC keeps reconnecting; calls report Unavailable meanwhile). With the server down, connect() now takes up to timeoutMs.

⚠ Check any loop that retries connect(). A loop bounded by an attempt count - for (i = 0; i < 30 && !db.connect(); ++i) sleep(1s); - cost about 30 s before 2.13.1 and costs up to 30 x (timeoutMs + 1 s) = 180 s with the default 5 s timeout. Under systemd that can outrun TimeoutStartSec (90 s is common), so a service started while the database is down - which a package postinst does on every upgrade - is killed mid-start instead of exiting cleanly. Bound such a loop by a wall-clock deadline, not an attempt count (found by smartbotic-vectorapi in its own units). isConnected() is the channel's last known state, not a live probe: use healthCheck() for "is the database answering now".

The full reason: FailureDetail (2.12.0+)

A status code alone is ambiguous - FailedPrecondition means a missing parent, a restricted delete and read-only mode - and it does not say which unique constraint refused a write. Client::FailureDetail does. Every call that takes a Failure& also has an overload taking a FailureDetail&, and for the calls that throw, Client::errorDetail(e) returns the same struct (or nullptr for an exception this client did not throw):

Client::FailureDetail why;
if (db.patch("calls", id, {{"vapi_call_id", callId}}, why) == 0) {
    if (why.reason == "unique_violation" && why.fields == std::vector<std::string>{"vapi_call_id"}) {
        auto existing = db.get("calls", why.conflictingId);   // that call is already recorded
    }
}

try {
    db.insert("files", {{"chat_id", 1}, {"file_id", "a"}});
} catch (const Client::AlreadyExists& e) {
    if (const auto* d = Client::errorDetail(e)) {
        // d->fields == {"chat_id", "file_id"}, d->values == {"chat_id":1,"file_id":"a"}
    }
}
reason Code Also set
unique_violation AlreadyExists fields (several for a composite), values (field -> value), conflictingId
duplicate_id (2.12.1+) AlreadyExists conflictingId = the id; fields empty - the identity collided, not a field
file_too_large (2.12.3+) InvalidArgument an upload over storage.files.max_file_size_mb
mime_type_not_allowed (2.12.3+) InvalidArgument an upload outside storage.files.allowed_types
missing_parent FailedPrecondition fields (the reference field), values (the missing id), relation
delete_restricted FailedPrecondition
read_only FailedPrecondition
version_conflict Aborted currentVersion
not_found NotFound
invalid_increment InvalidArgument fields (the path)
memory_pressure ResourceExhausted
view_write InvalidArgument
"" anything nothing further (transport errors, denials, ...)

Update and PatchDocument refusals now carry their code. Before 2.12.0 those two RPCs answered "not found", "version conflict", read-only, memory pressure and view writes in-band - status OK plus a message - and the client reported ErrorCode::Unknown. They still answer in-band, so an older client sees exactly what it always did, but the reply now says what the status would have been: a missing document is NotFound, a stale version Aborted (with currentVersion), and so on. Against a server older than 2.12.0 they are still Unknown, and FailureDetail holds only code and message.

Concurrency: update() vs patch()

When multiple clients modify the same document concurrently, choose the right method:

patch() — use for most updates (recommended). Merges only the specified fields on the server, atomically. Two clients can safely modify different fields simultaneously:

// Client A:                                    // Client B:
db.patch("users", "user-123",                   db.patch("users", "user-123",
    {{"name", "Alice Smith"}});                      {{"email", "alice@new.com"}});
// Result: both fields updated, nothing lost

update() — full document replacement with automatic retry. Uses optimistic locking internally (reads current version, writes with version check, retries on conflict). Use when you need to replace the entire document:

Every field the stored document has and the new body lacks is REMOVED. Since 2.21.7 the server logs it (update of <collection>/<id> removed N field(s) the stored document had: ..., WARN, at most once a minute per collection). If you see that line and did not mean to remove the fields, the call should have been a patch().

auto doc = db.get("users", "user-123");
(*doc)["name"] = "Alice Smith";
(*doc)["role"] = "admin";
db.update("users", "user-123", *doc);  // replaces entire document

Note: update() is "last writer wins" for complete replacement — if two clients modify different fields via update(), the last one overwrites the other's changes. Use patch() to avoid this.

updateIfVersion() — explicit optimistic locking. Use when you need to detect conflicts and handle them yourself:

auto doc = db.get("users", "user-123");
uint64_t version = (*doc)["_version"];
(*doc)["balance"] = (*doc)["balance"].get<int>() + 100;
if (!db.updateIfVersion("users", "user-123", *doc, version)) {
    // Version conflict — someone else modified the document
    // Re-read and retry, or report error to user
}

patchIfVersion() (2.12.0+) — a conditional partial update: merge some fields only if the document is still at the version you read. This is the right tool for "claim this task exactly once". updateIfVersion() replaces the whole document, so using it to flip one field means writing back everything you read - silently reverting any field someone else changed in between.

auto rows = db.find("tasks", {.filters = {Client::Filter::eq("state", "open")}, .limit = 1});
const uint64_t v = rows.at(0)["_version"];          // find() and get() return _version
Client::FailureDetail why;
if (db.patchIfVersion("tasks", rows[0]["_id"], {{"state", "claimed"}, {"owner", me}}, v, why) == 0) {
    if (why.code == Client::ErrorCode::Aborted) { /* someone else claimed it first */ }
}

The check and the write happen under one lock on the server: of any number of concurrent claims at one version, exactly one succeeds.

increment() (2.12.0+) — atomic counters. Adds numbers to fields in one locked read-modify-write, so concurrent increments never lose an update and no version loop is needed:

Client::FailureDetail why;
auto now = db.increment("stats", "2026-10-07", {{"calls", 1}, {"minutes", 3.5}, {"by.voice", 1}}, why);
// now = {"calls": 18, "minutes": 61.5, "by.voice": 4}
  • An absent or null field counts as 0; a dotted path creates nested objects.
  • Integer + integer stays an integer (overflow is refused); anything else is a double.
  • A field holding a non-number, a non-numeric delta, or document metadata is refused (InvalidArgument, reason invalid_increment, the path in fields), and then nothing is written - not even the other increments in the call.
  • The document must exist (NotFound otherwise). For a counter that may not exist yet: increment; on NotFound insert it under a fixed id with the starting value; on AlreadyExists (someone else just created it) increment again.

Collection schema (2.16.0+)

Optional, per collection. A collection without a schema behaves exactly as before. With one, the document every write would leave behind must conform to it, or the write is refused. It works like a SQL table definition, written as JSON Schema.

using Mode = smartbotic::database::Client::SchemaMode;
db.createCollection("people");
auto r = db.setCollectionSchema("people", {
    {"type", "object"},
    {"required", {"name"}},
    {"additionalProperties", false},            // unknown keys refused; omit to allow them
    {"properties", {
        {"name",  {{"type", "string"}, {"maxLength", 128}}},   // varchar(128)
        {"age",   {{"type", "integer"}, {"minimum", 0}}},
        {"email", {{"type", "string"}, {"format", "email"}}},
        {"nick",  {{"type", {"string", "null"}}}},             // nullable
        {"tags",  {{"type", "array"}, {"items", {{"type", "string"}}}}}}}});
if (!r.success) { /* r.error, r.violatingRows, r.examples */ }

db.insert("people", {{"name", std::string(130, 'a')}});
// throws Client::Error: InvalidArgument, reason "schema_violation",
// fields {"name"}, "schema violation: 'name' is 130 characters, longer than maxLength 128"

The language: a JSON Schema subset.

  • Types: type is one of string, number, integer, boolean, object, array, null, or an array of them. integer accepts 5.0, as JSON Schema says.
  • Objects: properties, required, additionalProperties (a boolean or a schema), minProperties/maxProperties.
  • Strings: minLength/maxLength, counted in characters (Unicode code points, not bytes). pattern uses RE2 syntax and is unanchored, as JSON Schema says. format is one of date-time (RFC 3339), date, email or uuid.
  • Numbers: minimum, maximum, exclusiveMinimum, exclusiveMaximum.
  • Arrays: items (one schema for every element), minItems/maxItems, uniqueItems.
  • Values: enum, const. Booleans work as subschemas: "x": false forbids x.
  • Annotations: title, description, default, examples, $schema, $id and $comment are accepted and ignored. In particular default is NOT applied to documents.
  • Anything else is refused when the schema is set ($ref, allOf/anyOf/oneOf/not, if/then/else, patternProperties, multipleOf, tuple items, ...), reason invalid_schema. A schema can therefore never look stricter than what is enforced.

What is validated: the user fields of the resulting document.

  • Not validated: the metadata (_id, _version, ...) and _vector. A vector's dimension is already enforced by the collection's vector_dimension.
  • Sensitive fields are judged by their plaintext, so maxLength on creds.password means the password's length, not its ciphertext's.
  • Every write path is checked: insert, upsert, update and updateIfVersion (the whole new body), batch insert (a refused item counts as an error), set add/remove, and restoreVersion/restoreToDate (an old version that breaks today's schema is refused, not resurrected).
  • patch and increment are checked on the MERGED result. A patch can break a rule by removing a required field (null removes a field in a merge patch) as easily as by setting a bad value.
  • A refused write leaves no trace: the document, its history and its expiry are untouched.

Not validated, by design: WAL replay at boot and replication apply. They replay writes this server or the origin already accepted.

A refusal is INVALID_ARGUMENT with reason schema_violation. FailureDetail::fields lists the violating paths: name, addr.zip, tags[2], and for a missing required key, the key itself. The message names each path, the rule and the size, up to 10 of them, then "(and N more)". Values are never echoed, because one may be a decrypted sensitive field.

Setting a schema on a collection that has data, and changing it. A schema can be set, replaced or removed at any time, and every change follows the same rule:

  • Enforce (default): every existing row is validated first. If any row violates the schema, the change is refused: success=false, with rowsChecked, violatingRows and up to 10 examples (each an id, a message and the fields).
  • Audit: the schema is applied regardless, and the same counts are reported. Later non-conforming writes are logged (rate-limited) and counted, and let through. Use it to arm a schema on live data, fix the rows, then switch to enforce.
  • No write slips past arming: the schema is armed under the collection's write lock BEFORE the existing rows are scanned. Every write either finished before (and the scan sees it) or starts after (and is checked).
  • So in enforce mode every row conforms. The exceptions are an audit-mode schema, and a replication follower whose origin has a different schema.
  • "At creation" means calling setCollectionSchema right after createCollection. Any row written in between is caught by the same existing-row check.

Reading it back: getCollectionSchema(collection) returns the schema exactly as set, its mode, and counters since it was armed (refusals, auditViolations). It returns nullopt when there is no schema. A read grant on the collection is enough.

Suggesting a schema from existing data: suggestCollectionSchema(collection, sampleLimit = 0) scans every row, or the first N, and returns a schema that every scanned row conforms to:

  • types: the union of what was seen ("integer" when every number was integral; "null" added where a value was null);
  • required: the keys present in every row;
  • additionalProperties: false;
  • format: date-time / date / uuid / email when every string at that path is one;
  • enum: a string field with at most 10 distinct values, each seen 3 times on average, and never for a sensitive field;
  • lengths and numeric ranges go into description only, not enforced: today's maximum is a fact about the data, not a rule.

Review it, edit it, then apply it with setCollectionSchema.

CLI: schema <coll>, schema-set <coll> '<json>'|@file [--audit], schema-drop <coll>, schema-suggest <coll> [limit].

Server version: all four client methods need a 2.16.0 server. Against an older one they refuse before sending, with FailedPrecondition and reason server_unsupported. The change calls report that reason in their result; the reads throw it.

Encrypted fields and schemas: a schema validates the PLAINTEXT of an encrypted field (see "Encryption at rest"); maxLength on a password means the password's length.

Indexes and unique constraints

db.createIndex("executions", "workflowId");              // speeds up queries on the field
auto r = db.createUniqueIndex("calls", "vapi_call_id");  // also refuses duplicates
auto c = db.createCompositeUniqueIndex("files", {"chat_id", "file_unique_id"});  // 2.12.0+

A unique constraint refuses a write that would give two documents the same value, with ErrorCode::AlreadyExists and reason unique_violation (see FailureDetail). Declaring one over data that already holds duplicates is refused, with examples in r.duplicateExamples, rather than accepted and left false.

Null is not a value (2.12.0+). Any number of documents may hold null for a unique field, or omit it - the SQL rule. A record that gets its external id later can be created with the field null. Before 2.12.0 two nulls collided while two absent fields did not. Null is still indexed: Filter::eq(field, nullptr) finds those rows. Note that patch() with a null value removes the field (merge-patch semantics); either way it is unconstrained.

Composite constraints (2.12.0+) make a combination unique - a received attachment per chat, a booking per (day, slot) - so the invariant lives in the schema, not in every writer. A document in which any of the fields is absent, null, an object or an array is not constrained. A composite backs no query; it only refuses duplicates. List them with listCompositeUniqueIndexes() (they do not appear in listIndexes(), which lists indexes on single fields) and drop one with dropCompositeUniqueIndex(collection, sameFieldList). From the CLI: unique-create <coll> <field> <field>..., unique-drop ..., and indexes <coll> shows them.

Constraints and indexes are declarations stored with the collection's config: they survive restarts and are re-armed at boot.

Dropping forgets them (2.12.2+). dropCollection removes the collection's declared indexes and constraints, and its other settings (relations_enforced, versioning, precision), so a new collection of the same name starts clean. dropProject does the same for every collection in the project and removes the project's documents. Before 2.12.2 the declarations survived the drop and a same-named collection inherited them; on such a name, dropCollection (even though the collection is gone) or dropIndex clears what was left.

Batch delete (2.12.0+)

Client::FailureDetail why;
auto r = db.removeManyAs("jobs", staleIds, "cleanup-job", why);   // one round trip
// r->deletedCount, r->deletedIds (in request order; an absent id did not exist)

Relations are enforced exactly as for removeAs(), and all-or-nothing on restrict: if any id is protected, nothing is deleted (reason delete_restricted). Every delete carries the actor onto its event.

Reading vectors back, and exporting a collection (2.13.0+)

_vector is moved out of a document on write (into the vector index), so an ordinary get/find never returns it. Ask for it explicitly:

auto doc  = db.get("chunks", id, Client::WithVector{});      // doc->at("_vector") if one is stored
auto docs = db.find("chunks", {.filters = {...}}, Client::WithVector{});

The vector comes back as "_vector": [floats] - the field insert() takes - so a document read this way can be written straight back and stays searchable. No "_vector" key means no vector is stored. Not available on a view.

Exporting a whole collection streams it instead of building one response:

auto sum = db.exportCollection("chunks", /*includeVectors=*/true, /*afterId=*/"",
    [&](const Client::ExportHeader& h) { /* h.vectorDimension, h.rowsAtSnapshot */ },
    [&](Client::ExportRow&& row) {
        // row.id, row.document (same shape as get()), row.vectorState, row.vector
        archive.write(row);
        return true;                       // false = stop after this row
    });
if (!sum.complete) { /* resume: exportCollection(..., sum.lastId, ...) */ }
  • One collection, never a project. The collection is named as everywhere else; a whole-tenant export is your loop over your own collections. Gated as an ordinary read of that collection (masks and row predicates apply).
  • One call is one snapshot: rows in id order, none skipped or repeated, and rowsSent == header.rowsAtSnapshot when complete.
  • Resuming with afterId = lastId is a new snapshot strictly after that id (an id that no longer exists works too: it resumes at the next id after it). It never repeats a row, but can miss one inserted during the gap whose id sorts before the cursor.
  • complete == false means the export stopped early: your handler returned false (that row counts as delivered and is lastId), or the server's time cap (header.maxStreamSeconds, 600 s) ended the stream. Resume from lastId.
  • It throws on a failed call, on a stream that ends without its trailer (it did not complete, whatever it delivered), on an unrecognised vector dtype (never reinterpreted), and with InvalidArgument / reason no_vector_index when vectors are asked of a collection with vector_dimension 0.
  • batchRows (default 256) is clamped to 1024, never refused; batches are also cut at 8 MB (or half the server's send limit, if lower). The clamp is in header.batchRowsCap - a cap, not a count: with large rows the real batches are smaller, which the callback API never shows.
  • A row too large for any one message (bigger than the server's max_send_message_size_mb) is never skipped silently: the export throws ResourceExhausted with reason row_too_large and the row's id in errorDetail(e)->conflictingId. The rows before it were delivered; resume with afterId = that id to continue without it, deliberately.
  • Any call refused for size by gRPC itself ("message larger than max", either direction) throws ResourceExhausted with reason message_too_large (2.13.0+), so it can be told from a rate limit or memory pressure, which share the code: retrying never shrinks a payload. ⚠ A row can reach that size without any single request doing so - repeated patch calls grow it - and is then unreadable by get; split such data or store it as a file.

vectorState, reported as stored and never guessed by the library:

State Meaning
Present the vector is stored; row.vector holds it
None the row was written without a vector (or an update() without _vector removed it)
Missing the row was written WITH a vector and its entry is gone - real data loss; never write it back as a plain document
Unknown no entry, and the row was written before 2.13.0, which recorded no marker. Any 2.13.0 write to the row (insert, update, upsert, patch, restore) records one, so touching a legacy collection once makes every row definite
Unspecified vectors were not requested

Since 2.13.0 a document and its vector are written in ONE transaction, so no reader (an export included) sees a row between the two; before, a snapshot could, and would have reported such a row as Missing.

Restoring is insert(collection, row.document, row.id) with row.document["_vector"] = row.vector when Present, into a collection of the same vector_dimension. The restored row has the same fields and a byte-identical, searchable vector - but fresh metadata: _created_at, _updated_at, _version and _created_by are stamped by the server, which accepts none of them from a caller. The originals stay in row.document in your archive; copy them into a field of your own before importing if you need them as data.

Reserved collection names: project:_name (2.17.1+)

A collection name starting with _ is internal. Written WITH a project (app:_cache) such a name is refused for reads and writes with INVALID_ARGUMENT, reason reserved_collection_name. Before 2.17.1 a write to one answered ok and could never be read back: it was kept in memory and the WAL but not in the on-disk store every read uses. dropCollection still accepts such a name, so leftovers can be removed. A bare _name is not qualified by the client and lives in the global namespace (the system collections); that is unchanged.

Reading a document's expiry: _expires_at (2.19.0+)

A document written with a TTL (insert/upsert ttlSeconds, patchWithTtl, or the collection's defaultTtlSeconds) now reads back with _expires_at: its absolute expiry, milliseconds since the epoch, beside _version and the other metadata. A document without an expiry has no _expires_at at all.

  • get, find and exportCollection all carry it - the server has always sent it, the client used to drop it. A 2.19.0 client reads it from any server.
  • It may lie in the past. Expiry is applied by a sweep (every second on a running server), and a restrict relation can deliberately hold a row past its TTL. A copy of the data directory taken while the server was stopped keeps expired rows until the next server that opens it sweeps them - which is how a backup can hold a row "121 hours past its deadline" that the live database no longer has. Compare _expires_at with the clock before concluding a row was lost.
  • Restoring: a restore must carry the expiry, or an expired row comes back PERMANENT (for an idempotency marker that suppresses the work it guards forever). For each exported row: if _expires_at is absent, insert without a TTL; if it is in the past, SKIP the row; otherwise insert with ttlSeconds = ceil((_expires_at - now) / 1000).
  • Filterable on a 2.19.0+ server (capability document_expires_at): Filter::lt("_expires_at", t) finds what expires before t; Filter::exists("_expires_at", false) finds documents that never expire. A document without an expiry is ABSENT for these filters (never "0"), so an upper bound does not match it. Not available as a sort key.
  • Never stored from a write body - it is a reserved name (below). A read document written back keeps or loses its expiry only through the TTL arguments, never through this field. Against a server older than 2.19.0 the 2.19.0 client strips it itself, so a round trip cannot store it there either.

Reserved names in a write body (2.13.0+)

_id, _version, _created_at, _updated_at, _created_by and _updated_by (and, since 2.19.0, _expires_at) are attached by every read and are never stored as fields. Since 2.13.0 the server strips them from every write body (insert, upsert, update, patch, batch insert), so a document read and written back - which is what a restore does - cannot store them. Before 2.13.0 insert/upsert/update stored them as ordinary fields that every read then hid: invisible, unfilterable (a filter on _version means the metadata), and carried into exports. Exports omit any such copies older rows still hold.

What this means for code that already writes them: nothing breaks. A body that carried these names was stored with them as hidden fields that no read returned; now they are simply not stored. Either way every read reports the real metadata, and a value written under one of these names was never readable back. Decorating a document with _id AFTER insert() returns (for a response, say) never reached the database at all.

Views

Views are named, read-only projections over collections. They filter which fields are returned and optionally enforce baked-in filters and default sort order. Views are ideal for:

  • Schema evolution — add fields to a collection without affecting consumers that query through a view
  • Security boundary — hide sensitive fields (passwords, tokens) and enforce row-level constraints (status=active, tenant=X)
  • API clarity — name and document a stable contract ("this view returns these fields with these filters")

Creating a view

using Op = smartbotic::database::Client::FilterOp;

// Simple: just project fields
db.createView("users_public",
              /*collection=*/"users",
              /*include=*/{"id", "name", "avatar_url", "profile.public_bio"});

// Full-featured: fields + filters + default sort
db.createView("active_admins",
              /*collection=*/"users",
              /*include=*/{"id", "name", "role"},
              /*exclude=*/{},
              /*where=*/{
                  {"status", Op::EQ, "active"},
                  {"role",   Op::EQ, "admin"}
              },
              /*defaultSort=*/smartbotic::database::Client::Sort{"name", false});

Querying a view

Views work like collections — use the view name in get(), find(), count():

auto user = db.get("users_public", "u1");         // projection applied
auto results = db.find("active_admins", {
    .filters = {{"department", Op::EQ, "eng"}},   // AND-merged with view's where
    .limit = 50
});
auto total = db.count("active_admins", {{"department", Op::EQ, "eng"}});

Inspecting and dropping

auto views = db.listViews();
auto info = db.getViewInfo("users_public");
db.dropView("users_public");

Semantics

Dimension Behavior
Filters View AND caller — view's where is always applied. Caller's filters are merged with AND. Consumers cannot escape the view's constraints.
Sort Caller overrides view — if the caller specifies a sort, it wins. Otherwise the view's defaultSort is used.
Include Whitelist — when non-empty, only those paths are returned.
Exclude Blacklist — ignored if include is non-empty; otherwise removes listed paths.
Metadata _id, _version, _created_at, _updated_at, _created_by, _updated_by are always returned regardless of include/exclude.
Nested paths Dot-notation supported: user.profile.name. Stops at arrays.
Writes Rejected — insert(), update(), patch(), upsert(), remove() on a view name return an error.
View-of-view Not allowed — views must target real collections.
Project scope (2.4.2+) Views belong to a project, exactly like collections. A view created by a client with project = "acme" is addressable only from that project, and two projects may each own a view of the same name. listViews() returns only the calling project's views.
Unknown name (2.4.2+) A name matching neither a view nor a collection makes find() throw std::runtime_error (gRPC NOT_FOUND). Before 2.4.2 it returned an empty result, which was indistinguishable from an empty collection.

Views and projects (2.4.2+)

View names are namespaced with the client's Config::project, so you keep using the bare name and the client qualifies it:

Client::Config cfg;
cfg.project = "acme";
Client db(cfg);

db.createView("adults", "users", {"name", "age"});  // -> acme:adults over acme:users
auto rows = db.find("adults", {});                  // resolves within acme only

A different workspace may define its own adults over its own users without colliding, and neither can read through the other's view.

Upgrading from <= 2.4.1. Views were unreachable through the client on 2.3.0-2.4.1: createView registered the bare name while every read path sent the project-qualified one, so lookups always missed and returned an empty result with no error. Existing view definitions are re-keyed into the default project automatically on first boot of 2.4.2 (idempotent, logged as ViewManager: re-keyed N legacy view(s)). No operator action required. Callers that treated the empty result as "view has no rows" will start seeing real rows.

Via migrations (recommended)

{
  "version": "020",
  "name": "create_active_admins_view",
  "operations": [
    {
      "type": "create_view",
      "name": "active_admins",
      "collection": "users",
      "include": ["id", "name", "role"],
      "where": [
        {"field": "status", "op": "EQ", "value": "active"},
        {"field": "role",   "op": "EQ", "value": "admin"}
      ],
      "default_sort": {"field": "name", "descending": false}
    }
  ]
}

The op field in where filters accepts either a string name (EQ, NE, GT, GTE, LT, LTE, IN, CONTAINS, EXISTS, REGEX, SEARCH) or the matching integer. Migrations are idempotent — re-running a migration that creates an existing view is a no-op.

Why AND-merge filters?

A view's filters are applied server-side, before projection, and a consumer filter is ANDed on top rather than replacing them — so a caller querying active_admins cannot widen the result set beyond what the view defines. That makes a view a reliable schema and shape contract: what comes back through this name is always a subset of what the view allows.

A view is NOT a security boundary. Earlier revisions of this guide described view filters as "a security enforcement boundary" and compared them to row-level security. That was wrong, and should not be used as the basis of a threat model. Three reasons:

  1. There is no caller identity. Authentication (2.4+) compares a bearer token against a flat list of shared keys per listener. It attaches no principal to the call, so the server cannot know who is asking — and every key holder has identical, complete access.
  2. The underlying collection stays readable. Views only reject writes on a view name. find("active_admins") narrows; find("users") does not. Nothing stops a client bypassing the view entirely.
  3. Projects are not a boundary either. Config::project is chosen by the client, and a fully-qualified other_project:collection name is accepted from any client, so namespaces isolate naming, not access.

Views constrain what a cooperating client sees. Treat them as ergonomics and API hygiene. Real row- and column-level security requires a per-principal identity and a policy evaluated at every read handler; that is planned but not present today.

Related: field-level encryption (sensitiveFields) is encryption at rest, not access control. Sensitive fields are decrypted for every authenticated reader; the protection is against someone reading data files, snapshots, or backups, not against a client.

Encryption at rest (rewritten in 2.17.0 - read this if you store secrets)

encryption.enabled defaults to true. Since 2.17.0 a value is stored encrypted (AES-256-GCM, random IV) when ANY of these applies:

  1. The collection was created with encrypted=true: every non-null value of every document, strings as $ENC$..., other types as $ENCJ$... so a read restores the type. Property NAMES stay plaintext. The embedding (_vector) is never encrypted: similarity search compares its numbers, so an encrypted collection searches, exports and re-imports like any other (the text beside the vector is encrypted; filters on it are refused). Note that an embedding can reveal something about its source text. In 2.17.0 and 2.17.1 the vector WAS encrypted, so every insert carrying a vector into an encrypted collection was refused ("type must be number, but is string"); fixed in 2.17.2.
  2. Its path is in the collection's sensitive_fields (or lies under one).
  3. Its name matches a built-in pattern, at ANY depth, top level included: password, secret, token, api_key, apiKey, credentials (exact name, case-insensitive) - and everything under such a field, array elements included. The WHOLE last path segment must equal the name: refreshToken, apiKeyHash and openai_api_key do NOT match (no substring or suffix match). Name a secret one of these, or put the collection under rule 1.

A number, bool, object or array becomes one $ENCJ$ string, so grepping a data file for a known number finds nothing: that is encryption working, not data loss - encryption-verify and an ordinary read are the checks.

⚠ Before 2.17.0 only part of this was true, and nothing said so:

  • (1) and (2) did nothing at all. The options were stored and reported, and no code read them.
  • (3) matched NESTED fields only, so a top-level password was plaintext.
  • patch never encrypted, migration-file ops never encrypted, and strings inside arrays were neither encrypted nor decrypted.

If you relied on any of these, your data was plaintext at rest - and so are any backups or copies taken before the upgrade.

The upgrade migrates existing data, once, at the first 2.17.0 boot:

  • What is encrypted: every stored value the rules above require, in place (same version, no new history entry), and every stored history version.
  • The old plaintext is then removed from the database files: the WAL is rotated, a verified snapshot is taken, every older snapshot and WAL file is deleted, and every LMDB environment is compacted (LMDB is copy-on-write, so freed pages still hold old bytes until compacted).
  • No double encryption: a value already carrying $ENC$/$ENCJ$ is never encrypted again, so the pass is idempotent.
  • Boot time: it is logged (v2.17 at-rest) and extends the systemd start timeout as it goes. What it costs: a scan of every row and every history file (history is REWRITTEN only where a value must change), then compacting every project's LMDB env, which costs about the time to copy the LARGEST data.mdb. Measured: 22,298 rows / 626 MB env / a 230 MB history file that needed rewriting took about 6.5 minutes; 24,733 rows / a 339 MB env / 192 MB of history that needed no rewriting took 190 s, of which 167 s was compacting that one env (measured by a consumer, under a 900 MB memory cap).
  • Memory: plan with the ANONYMOUS memory. RSS / VmHWM also count the file-backed LMDB map, which the kernel reclaims under pressure rather than killing anything, so an RSS above 1 GB on a 2 GB host is not by itself a reason to stop it. Measured per phase (cgroup memory.stat, 22.5k documents, 2.17.2):

| phase | anonymous max | page cache max | |---|---|---| | boot + row pass | 456 MB (load spike, then ~375) | 218 MB | | seal snapshot (5 s) | 774 MB | 259 MB | | compaction (3 min) | 373 MB, flat | 263 MB |

The peak is the seal's snapshot: the in-memory store serialized, compressed and read back to verify, roughly the working set again on top of it. It is the same code path as the server's routine snapshots, so a host that survives those survives the seal; the peak RSS at a routine "Snapshot created" is the number to check. Compaction adds no anonymous memory. Progress is NOT persisted per step: a boot killed before the end repeats the row pass (fast, skips what is done), the snapshot and every compaction, so a host that cannot fit the snapshot fails at the same point on every boot - restore the pre-upgrade backup rather than retrying. Since 2.17.1 history is rewritten one record at a time.

  • Installing without migrating yet: the server package's postinst starts or restarts the service with systemctl directly, so a policy-rc.d that denies starts does NOT hold it (reported by a consumer who tried). Mask the unit instead: systemctl mask smartbotic-database, install, check what you need, then systemctl unmask smartbotic-database && systemctl start smartbotic-database - the migration runs at that start.
  • Measured elsewhere: on a 2 GB production droplet (34,456 rows, a 343 MB env) the whole first boot took 50 s; the same data in a container on a dev box took 204 s. A containerised copy is a safe upper bound, not a performance model of the target host.
  • What it cannot reach: copies made BEFORE that boot - backups, pre-upgrade copies, replicas, released disk blocks. Rotate any credential that was stored in plaintext.

Switching encryption on for an existing collection: createCollection(name, ..., encrypted=true) on an existing collection now switches it on (never off), and sensitive_fields given that way are added. Its rows and history are encrypted immediately. The old plaintext copies are removed at the next restart: encryption-verify reports sealed: NO until then. That next restart compacts again (about the time to copy the data.mdb involved), so plan it as a window, not as an ordinary 15-second restart. In 2.17.1 it compacts EVERY project, and is requested whenever the flag changes; since 2.17.2 it is requested only when plaintext was actually rewritten, and compacts only that collection's project. Later restarts are ordinary.

This includes the defensive idiom. A client that calls createCollection(name, ..., encrypted=true) on every startup changes nothing when the collection already has the flag, but the FIRST time it runs against 2.17.x on a collection without its own flag (for example one encrypted only through a bare alias name) it switches the flag on and so requests that compacting restart. Upgrade the database, start such clients once, then restart the database inside the same maintenance window, so the compaction does not surface weeks later as an unexplained slow restart. (Reported by smartbotic-vectorapi, whose prod plan now has exactly these three steps.)

Check the flag rather than assume it. A bootstrap that calls createCollection(..., encrypted=true) only when the collection does not exist yet never sets it when an earlier write already created the collection implicitly. Calling createCollection(..., encrypted=true) unconditionally fixes it. To check, use encryption-verify (an encrypted collection is marked [encrypted]). Since 2.17.1 smartbotic-db-cli info <collection> also reports the ENFORCED rule; in 2.17.0 it showed only the collection's own options, which can disagree with the bytes in either direction (options declared on a bare alias name are enforced but were not shown).

Encrypted fields cannot be compared, so comparisons are REFUSED with INVALID_ARGUMENT, reason encrypted_field, the fields named:

  • a find/count/similaritySearch filter or a sort on an encrypted field, or a SEARCH filter on an encrypted collection;
  • an index, unique or composite constraint, or relation on an encrypted field;
  • listing an encrypted field's index values;
  • an increment of an encrypted value;
  • set operations on an encrypted collection (FAILED_PRECONDITION).

The refusal is permanent: retrying cannot succeed. The calls that throw carry it in Client::errorDetail(e).reason. The calls that answer with a bool or a result struct (createIndex, createUniqueIndex, createCompositeUniqueIndex, createRelation, setAdd, setRemove) gained FailureDetail& overloads in 2.17.0; the original overloads cannot tell this refusal from an outage, so use the new ones wherever a caller decides between "fix the request" and "retry".

Before 2.17.0 such a comparison ran against ciphertext under a random IV and silently matched nothing - an empty result indistinguishable from "no such row". An index already declared on a field that is now encrypted is disarmed at boot and named in an ERROR line; drop it. To look a record up by a secret (an API key, a token), store a keyed hash of it in a field with a non-sensitive name, look up by that, and keep the secret itself encrypted. Filters on metadata (_id, _created_at, ...) and on non-sensitive fields of a non-encrypted collection work as before.

Reading is unchanged: Get, Find, SimilaritySearch, view reads, exports and version reads all return plaintext. The same ciphertext in consecutive versions is correct (an unchanged sensitive value keeps its stored ciphertext).

Auditing: smartbotic-db-cli encryption-verify [collection] / Client::verifyEncryption() (admin) walks every stored row and history version and counts:

  • values correctly stored as ciphertext;
  • plaintext where ciphertext is required;
  • ciphertext of ciphertext (double encryption);
  • ciphertext the key cannot open; and whether the migration's seal is complete. It exits 1 on any finding, and also while unsealed. Since 2.17.2 the CLI prints CLEAN (UNSEALED: ...) while a reseal is pending: the live store is clean but old plaintext copies remain on disk until the next restart.

What CLEAN means: everything the rules above REQUIRE to be encrypted is encrypted, once, and decrypts. It does not mean "nothing sensitive is in the clear": a secret stored under a non-sensitive name in a collection that is not encrypted is invisible to it by design.

⚠ Against a 2.17.0 server, do not run it on a live database: it read history under the global history lock, so every history-recording write, in every collection, waited while a large history file was read (minutes for a 230 MB file; seen as Deadline Exceeded on unrelated collections). 2.17.1 reads history without that lock.

To turn encryption off set storage.encryption.enabled: false. Existing ciphertext then reads back as the literal $ENC$ string, so do it before storing such fields, not after.

Access Policy — row and column level security (2.7.0+)

Per-project row- and column-level access control. Off by default: a project with no policy behaves exactly as it did before 2.7.0, so upgrading changes nothing until you turn it on.

Before 2.7.0 there was no access control beyond authentication. Every API-key holder had identical, complete access. Views were never a boundary - see the note under "Why AND-merge filters".

The model

  • Principal = the name of the API key the request arrived with. Keys became named in 2.7.0:

    "auth": { "required": true, "keys": [
      { "name": "shadowman", "key": "<base64>" },
      { "name": "callerai",  "key": "<base64>" } ] }
    

    A bare string key still works and maps to the reserved principal unnamed. A request with no usable token is the reserved principal anonymous - which is grantable, so the local CLI keeps working by explicit policy rather than by an implicit hole. anonymous and unnamed are refused as key names.

  • Policy = one record per (project, principal) granting read/write per collection or file type, with an optional column mask and row predicate.

  • admin grants everything within a project plus the right to edit policy.

Turning it on safely

Enabling is refused unless some policy in the project has admin: true - lockout is prevented structurally, not by care. Removing the last admin of a secured project is refused for the same reason.

Always arm a live project in audit mode first. Audit evaluates every policy, logs what it would deny, and allows the request:

smartbotic-db-cli policy-set acme ops '{"admin":true}'
smartbotic-db-cli policy-set acme svc \
  '{"collections":{"users":{"read":true,"mask":["ssn"],
     "row":[{"field":"tenant","op":0,"value":"acme"}]}}}'

smartbotic-db-cli security-set acme on audit     # watch the log
smartbotic-db-cli security-set acme on enforce   # then commit
smartbotic-db-cli security acme                  # show current state
smartbotic-db-cli policies acme                  # list principals

Once enforcing, the project is deny-by-default: a principal with no matching rule gets nothing.

What enforcement covers

Every RPC that reads or writes user data. Notably including the ones that are easy to forget:

  • Subscribe is filtered per event, since an empty collection list means "everything" and there is no single name to authorise up front. Masked columns are stripped from event payloads.
  • Version history (GetVersionHistory, GetDocumentVersion, RestoreVersion, RestoreToDate) - it returns previous document bodies, so leaving it open would bypass a column mask entirely.
  • Enumeration and counts - ListCollections, ListViews, ListFiles, Count, GetCollectionInfo, GetMemoryStats filter or refuse. A name or a document count is information about data you may not read. ListFiles also recomputes total_count, which would otherwise report how many files exist in types you have no grant for.
  • Batch and set operations, which are ordinary reads and writes.
  • SimilaritySearch (2.14.0+): row predicate, masks and the masked-filter refusal exactly as Find. Before 2.14.0 it checked the grant and then returned every row and every column - on a secured project a vector search saw rows and fields find() refuses.

Semantics worth knowing:

  • A column mask removes fields from every document returned, and filtering on a masked field is refused - salary > 100000 would otherwise leak a value you cannot read.
  • A write touching a masked field is denied, not silently dropped. Silent field loss is worse than an error.
  • A row predicate hides documents outright: Get reports not-found rather than "forbidden", because the difference is itself information.
  • System collections (_policies, _views, …) require admin. _policies describes the whole access model.

Denials are visible to your code

get, exists, find, findWithMetrics and count throw on a denial rather than returning empty. This is deliberate: a denial that looked like "no data" would leave your application unable to tell "you may not see this" from "there is nothing to see", and it would silently take the wrong branch.

Limits

  • Service-wide operations cannot be expressed per project. GetStats, SetReadOnly, CreateProject and DropProject require admin of some secured project; ListProjects filters. The real boundary for operator surfaces is listener separation - do not expose an admin listener publicly.
  • HealthCheck and GetReadOnlyStatus are intentionally open; they expose no user data.
  • Auth requires TLS. gRPC aborts if an auth processor is attached to insecure credentials, so auth.required: true with tls.enabled: false is refused at startup.

Collection Configuration

Per-collection runtime settings. Currently supports timestamp precision; extensible for future knobs.

Timestamp precision

Every document carries _created_at and _updated_at — int64 timestamps since epoch.

Since 2.2.0 the default is nanoseconds (ns). It was milliseconds up to 2.1.x. The flip was made because collections that receive rapid-fire writes (LLM streaming chunks, agent tool loops) saw ties at ms resolution that made ORDER BY _created_at ambiguous; ns gives unique, strictly ordered timestamps out of the box. Collections that already had a stored config keep their value — only collections created after the upgrade without an explicit configureCollection() inherit the new default.

using Cfg = smartbotic::database::Client::CollectionConfig;

// Default since 2.2.0: ns (no configuration needed)
auto id = db.insert("llm_tokens", {{"token", "hello"}});
// doc["_created_at"] is ~19 digits, nanoseconds since epoch

// Opt a collection back to milliseconds
db.configureCollection("logs", Cfg{"ms"});

// Future inserts into logs get ms-precision timestamps
auto id2 = db.insert("logs", {{"msg", "..."}});
// doc["_created_at"] is ~13 digits, milliseconds since epoch

Note: Client::CollectionConfig::timestampPrecision still defaults to "ms" in the header, so Cfg{} sends an explicit "ms" rather than meaning "server default". Pass the precision you want explicitly, or leave the string empty to mean "leave unchanged" (2.4.5+, see partial updates below).

Reading the config

auto cfg = db.getCollectionConfig("logs");
std::cout << cfg.timestampPrecision << std::endl;  // "ms"

bool explicit_set = db.hasCollectionConfig("logs");        // true
bool default_only = db.hasCollectionConfig("llm_tokens");  // false (still ns default)

getCollectionConfig() covers timestamp precision and versioning. Relation enforcement comes from the same RPC but is read with its own accessor - see Relation enforcement on/off below.

Version history on/off (2.4.5+)

Version history can be switched per collection, on a collection that already exists and already holds data:

Cfg off;
off.timestampPrecision = "";      // empty = leave precision unchanged
off.versioningEnabled  = false;   // stop recording new versions
db.configureCollection("metrics_events", off);

// ... later, turn it back on
Cfg on;
on.timestampPrecision = "";
on.versioningEnabled  = true;
db.configureCollection("metrics_events", on);

Semantics:

  • Reversible. Disabling stops new versions being recorded. History already on disk stays readable via getVersionHistory() / getDocumentVersion(), so re-enabling simply resumes appending.
  • Not the same as maxVersions = 0, which means "keep unlimited history". versioningEnabled = false means "keep none".
  • Durable. The setting lives in the _collection_meta system collection, so it survives restarts through the normal WAL + snapshot path.
  • Takes effect on the next write.

Trimming history that already exists (2.17.1+). createCollection(name, ..., maxVersions=N) on an EXISTING collection with a cap lower than before (or any cap over unlimited) rewrites its history file keeping the newest N versions per document. It runs inside the call. Since 2.17.2 it holds only that collection's history lock: only writes that record history in THAT collection wait. In 2.17.1 it held the store's global lock, so every collection's operations waited: on 2.17.1 run it at a quiet moment, one collection at a time. Before 2.17.1 the call changed the setting and trimmed nothing, and no supported call could cut back history kept with maxVersions = 0.

  • From the CLI (2.18.1+): smartbotic-db-cli configure <collection> [--versioning on|off] [--max-versions N] does this safely: it passes the current default TTL back, refuses --max-versions 0 (unlimited, not off), leaves timestamp precision alone, and prints what it changed and how long the prune took. info prints default_ttl_seconds.
  • ⚠ Pass the collection's current defaultTtlSeconds. createCollection on an existing collection applies every argument that differs, and a default TTL of 0 is a real value ("no default expiry"): a prune call written as createCollection(name, 0, false, N, 0) clears an existing default TTL for every later insert. Read it first with getCollectionInfo(name)->defaultTtlSeconds. (encrypted=false never downgrades and vectorDimension=0 is ignored.)
  • The current documents are never touched: only the history file is rewritten (tmp + atomic rename), records are copied as stored, and every document keeps its newest N versions (N >= 1).
  • Measured (2.18.0): a 56 MB history file pruned in 3.9 s, a 230 MB one in 10.3 s. Writes that record history in THAT collection waited for the whole prune; writes to other collections stayed under 120 ms.
  • To stop recording history use configureCollection(versioningEnabled=false), not maxVersions=0 (which means unlimited). It only flips a config flag and needs no window; it does not reclaim history already written. There is no call that discards a live collection's history outright: the floor is maxVersions=1, which keeps the newest version of every document id ever written, deleted ones included.

Relation enforcement on/off (2.11.0+)

Whether declared relations are enforced is a per-collection setting. It defaults to on: declaring a relation names its child and parent, so the declaration is the opt-in. Switching it off is the escape hatch for a bulk import, and it is not retroactive - references left dangling while it was off are found only by relation-check.

It is both writable and readable, but not through getCollectionInfo(). CollectionInfo describes what a collection is (creation-time options, size); settings that can change afterwards are served by the GetCollectionConfig RPC, and this one has its own accessors because adding a member to a public client struct changes its size under an unchanged soname, which crashes consumers already installed against the old layout.

db.setRelationsEnforced("executions", false);   // partial update: touches only this

// For code that decides whether it may rely on enforcement.
// Fails toward `true` if the read itself fails.
bool relied_on = db.getRelationsEnforced("executions");

// For anything that SHOWS the setting (2.11.4+). No value means the setting
// could not be determined, so a UI can render "unknown" instead of a guess.
std::optional<bool> shown = db.tryGetRelationsEnforced("executions");
Reading Meaning
true Enforced. Either never configured (the default) or explicitly enabled.
false Someone disabled it. Deletes and writes on this collection skip relation checks.
no value Could not be determined: the server was unreachable, the read was denied, or the server predates 2.11.0 and has no relations. Never means "unset". Does not throw.

"Never configured" and "explicitly enabled" are deliberately one reading: they behave identically on every write and delete, and the server stores the setting, not a record of who chose it. The distinction an operator needs is enforced versus not, and false appears only when someone turned it off.

From the CLI:

smartbotic-db-cli configure-relations executions        # show the current state
smartbotic-db-cli configure-relations executions off    # change it
smartbotic-db-cli info executions                       # also prints relations_enforced

Over raw gRPC, GetCollectionConfigResponse.config.relations_enforced is populated on every reply from a 2.11.0+ server.

Partial updates (2.4.5+)

configureCollection() is a partial update. Fields you leave unset are preserved, not reset:

  • empty timestampPrecision → precision unchanged
  • unset versioningEnabled (std::nullopt) → versioning unchanged

    Cfg justPrecision;
    justPrecision.timestampPrecision = "ms";   // versioningEnabled stays nullopt
    db.configureCollection("logs", justPrecision);
    // -> precision becomes ms; versioning is left exactly as it was
    

On getCollectionConfig(), versioningEnabled is always populated with the collection's effective value rather than the "leave unchanged" sentinel.

Before 2.4.5 this RPC replaced the whole config. That was harmless while precision was the only field, but it is why versioning_enabled is declared optional in the proto: a plain proto3 bool defaults to false, so any precision-only call would otherwise have silently switched versioning off.

What configureCollection does NOT do

It does not convert existing timestamps. Flipping a collection from ms to ns only affects future inserts. Pre-existing docs keep whatever precision they had. This keeps the config flip atomic and reversible.

Consequences of mixed precision within one collection:

  • int64 ordering within the collection is still consistent (ms values are always < 10^15, ns values are always > 10^15, so ns docs sort after ms docs). Queries don't break.
  • But the ns-labeled docs appear to be in the future relative to the ms-labeled docs unless you convert.

Migrating existing timestamps

When you're ready to convert legacy data, run the migration helper during a planned maintenance window:

auto result = db.migrateCollectionTimestamps("llm_tokens",
                                              /*fromPrecision=*/"ms",
                                              /*toPrecision=*/"ns");
if (result.success) {
    std::cout << "migrated " << result.rowsMigrated
              << " rows, skipped " << result.rowsSkipped << std::endl;
} else {
    std::cerr << "failed: " << result.error << std::endl;
}

Semantics:

  • ms → ns: multiply _created_at / _updated_at by 10^6
  • ns → ms: divide by 10^6 (truncation — loses sub-ms precision)
  • Idempotent and resumable. Rows that are already in the target range are detected via a 10^15 threshold and skipped. If the migration is interrupted (network drop, deadline), rerun it — already-converted rows will count as rows_skipped.
  • from == to is a no-op success.
  • Metadata-only — document version numbers are NOT incremented, WAL is not appended, history is not updated. This is an infrastructure rewrite, not a user-visible change.
  • Deadline: the client's RPC timeout for this call is 10 minutes — large collections may take a while.

Recommended workflow for switching precision on production data

  1. Schedule a maintenance window (writes against the collection may pause briefly if needed).
  2. Call configureCollection(name, {ns}) — atomic config flip; future writes immediately use ns.
  3. Call migrateCollectionTimestamps(name, "ms", "ns") — converts existing docs.
  4. Verify with a sample read that _created_at values are now in the ns range.
  5. Resume normal traffic.

Between steps 2 and 3, new writes are ns and old docs are ms — this is temporary but normal. Ordering still works because the 10^15 threshold cleanly separates the two ranges.

Via migrations

To set timestamp precision declaratively, call db.configureCollection() from your consumer project's startup code. The configure_collection migration operation will be available in a future version.

{
  "version": "021",
  "name": "llm_tokens_ns_precision",
  "operations": [
    {
      "type": "configure_collection",
      "collection": "llm_tokens",
      "config": { "timestamp_precision": "ns" }
    }
  ]
}

Recovery & Read-Only Mode

smartbotic-database uses WAL + snapshots for durability. When starting up, the server tries to recover state from the newest snapshot and replay WAL entries since that snapshot. If something goes wrong, it uses a tiered recovery system modeled on MySQL's innodb_force_recovery.

Recovery modes

Level Name Behavior
0 normal Load latest snapshot + replay WAL. Default. If auto_escalate=true (default), falls back to older snapshot automatically when latest is corrupt.
1 snapshot_fallback Try snapshots newest→oldest, first that loads wins.
2 wal_only Ignore snapshots, replay WAL from sequence 0. Slow on large DBs.
3 best_effort Try snapshot_fallback, then fall through to wal_only.
4 force_empty Start empty. Snapshots + WAL preserved on disk for forensics.

Operator escalation path when recovery fails:

# After a refuse-to-start, try older snapshots
smartbotic-database --recovery-mode=snapshot_fallback

# If that still fails, replay WAL from scratch (slow)
smartbotic-database --recovery-mode=wal_only

# Last-ditch: try everything
smartbotic-database --recovery-mode=best_effort

# Absolute last resort: start empty (data preserved on disk)
smartbotic-database --recovery-mode=force_empty

Or set in config.json:

"persistence": {
    "recovery": {
        "mode": "normal",
        "auto_escalate": true,
        "allow_empty_on_fresh_install": true
    }
}

The CLI flag overrides the config for one-shot recoveries.

Auto-readonly on non-trivial recovery

If recovery used anything other than "latest snapshot loaded cleanly," the DB boots in read-only mode. This is a safety feature — writing onto a possibly-stale state can corrupt your data further. The operator must explicitly acknowledge the state before writes resume.

On startup you'll see (at ERROR level):

[ERROR] Database booted in READ-ONLY mode after non-trivial recovery
        Reason: fell back to snapshot snapshot-20260419-090719.dat because
                snapshot-20260419-100747.dat failed: body truncated

Writes will be REJECTED until you acknowledge this state:
  smartbotic-db-cli unlock                  # live, no restart
  smartbotic-database --force-readwrite     # on next restart

Workflow: recovering a broken instance

  1. Preserve forensics. Stop the service, snapshot /var/lib/smartbotic-database/ before anything else.
  2. Diagnose. Start the server (default mode = normal). It will either recover cleanly or refuse with a clear banner. Use smartbotic-db-cli status to see what happened.
  3. Escalate. If recovery refused, restart with --recovery-mode=snapshot_fallback (and upwards as needed).
  4. Extract data. While the DB is in read-only mode, connect with the CLI or client library and read whatever survived. Dump/export facilities are planned for v1.7.0.
  5. Decide.
    • Data looks complete → smartbotic-db-cli unlock to resume writes.
    • Data is missing/stale → don't unlock. Extract to an external backup, then wipe /var/lib/smartbotic-database/ and start clean.

Client API

// Acknowledge auto-readonly state and resume writes
db.unlock();

// Force read-only for maintenance (regardless of recovery outcome)
db.lock();

// Inspect state + recovery outcome
auto s = db.getReadOnlyStatus();
std::cout << "read-only:        " << s.readOnly << "\n"
          << "reason:           " << s.reason << "\n"
          << "recovery outcome: " << s.recoveryOutcome << "\n"
          << "expected snap:    " << s.expectedSnapshot << "\n"
          << "snapshot used:    " << s.snapshotUsed << "\n"
          << "failure reason:   " << s.failureReason << "\n"
          << "WAL replayed:     " << s.walEntriesReplayed << "\n"
          << "snapshots tried:  " << s.snapshotsAttempted << "\n";

CLI

# Inspect read-only + recovery state
smartbotic-db-cli status

# Acknowledge non-trivial recovery and accept writes
smartbotic-db-cli unlock

# Manually lock (e.g. before a maintenance window)
smartbotic-db-cli lock

Snapshot durability settings

Under persistence.snapshots:

"snapshots": {
    "validate_after_write": true,        // verify every snapshot immediately after creation
    "cleanup_only_if_verified": true     // never evict old snapshots if the new one failed validation
}

Both default to true — turn off only if you really know what you're doing (disables protections against silent writer corruption).

Exit codes

Code Meaning
0 Normal shutdown
1 Generic error
10 Recovery refused. Snapshot or WAL failure + mode=normal + data exists on disk. Operator must escalate the recovery mode or pass --force-readwrite.
11 Config invalid (e.g. bad --recovery-mode value)

--force-readwrite

Bypasses the auto-readonly guard on non-trivial recovery. Use after you've reviewed the recovery state via smartbotic-db-cli status and are certain writes onto that state are safe.

# After confirming recovery state looks good
smartbotic-database --force-readwrite

Querying

// Find with filters (equality is default)
smartbotic::database::Client::QueryOptions opts;
opts.filters = {
    {"status", "active"},   // EQ (default) — 2-arg Filter constructor
    {"role", "admin"},      // EQ
};
opts.sortField = "name";
opts.sortDescending = false;
opts.limit = 50;
opts.offset = 0;

auto docs = db.find("users", opts);
for (const auto& doc : docs) {
    std::cout << doc["name"] << std::endl;
}

// Find all documents in a collection
auto allDocs = db.find("users");

// Count
uint64_t total = db.count("users");
uint64_t admins = db.count("users", {{"role", "admin"}});

Filter operators

Filters support a range of operators via Client::FilterOp. The 2-argument Filter(field, value) constructor defaults to EQ — existing brace-init code continues to compile and behave the same. To use other operators, pass the operator explicitly with the 3-argument constructor:

using Op = smartbotic::database::Client::FilterOp;

smartbotic::database::Client::QueryOptions opts;
opts.filters = {
    {"age", Op::GTE, 18},                                             // age >= 18
    {"status", Op::NE, "deleted"},                                    // status != "deleted"
    {"tags", Op::CONTAINS, "admin"},                                  // tags array contains "admin"
    {"role", Op::IN, nlohmann::json::array({"admin", "moderator"})},  // role IN [...]
    {"email", Op::REGEX, ".*@example\\.com$"},                        // regex match
    {"name", Op::SEARCH, "alice"},                                    // full-text search
    {"deleted_at", Op::EXISTS, false},                                // field does NOT exist
};
auto docs = db.find("users", opts);
Operator Semantics Value type
FilterOp::EQ field equals value any JSON
FilterOp::NE field does not equal value any JSON
FilterOp::GT field > value number or string
FilterOp::GTE field >= value number or string
FilterOp::LT field < value number or string
FilterOp::LTE field <= value number or string
FilterOp::IN field value appears in the supplied array JSON array
FilterOp::CONTAINS field (array) contains the supplied value any JSON
FilterOp::EXISTS field presence check (true = must exist, false = must not) bool
FilterOp::REGEX field matches the supplied RE2 pattern (see below) string
FilterOp::SEARCH full-text search across document ID and string fields string

Comparison rules (2.18.0+, capability typed_range_filters):

  • GT/GTE/LT/LTE match only number-to-number or string-to-string. A field holding null, a boolean, an object or an array, or a value of the other kind than the bound, never satisfies a range; a null or boolean bound matches nothing. 5 and 5.0 are both numbers. Strings compare byte-wise.
  • Before 2.18.0 ranges compared ACROSS JSON types in the order null < boolean < number < string, so an explicit null or true matched year <= 2025 and the string "1900" matched year >= 2025. A single bound silently over-matched; anything that relied on that was already wrong.
  • An absent field never matches EQ, NE, a range, IN, CONTAINS or REGEX (unchanged); only EXISTS false selects it. An explicit null is present: EXISTS true matches it, and EQ null matches it.
  • EQ/NE keep JSON equality: NE matches values of another type.
  • Sort order is unchanged and differs from filtering: ascending puts null first and rows WITHOUT the field last (descending the reverse). A list view that sorts and filters on the same field should bound the filter on both sides, so rows the sort would place at either end are excluded consistently.
  • The value's JSON type is what you sent. A filter value parsed from text can change type with its content (2026.1 is a number, 2026.1.3 a string), and a number never matches a string under these rules.

REGEX (2.20.0+, capability re2_regex_filters):

  • Patterns use RE2 syntax (the same engine as a collection schema's pattern). Matching is a SEARCH: the pattern may match anywhere unless you anchor it with ^/$. A value that is not a string never matches.
  • Matching takes time linear in the value's length, whatever the pattern. Before 2.20.0 the server used std::regex, which backtracks: a caller-supplied pattern such as (a+)+$ against a long run of a could tie up a server thread for minutes (measured: past a 20 s deadline on a 5,001-byte value, still running after the client had given up).
  • UTF-8 aware: [áÁ] matches one character and . matches á. Under std::regex a character class matched single bytes, so sz[áÁ]mfejt never matched számfejt and [öÖ] matched any text holding another accented letter (they share a lead byte).
  • (?i) makes a pattern case-insensitive, non-ASCII letters included ((?i)BÉR matches bér). There is no separate flag.
  • A pattern that does not compile is refused by find, count, similaritySearch and createView: INVALID_ARGUMENT, reason invalid_pattern, fields = the filter's field, and the message carries RE2's error. Before 2.20.0 it was silently treated as "no match", so a typo looked like an empty result. To read the reason from a READ call (find, count, similaritySearch) a consumer also needs a 2.17.0 or newer client library; older clients see the InvalidArgument code without the detail.
  • ⚠ Breaking for patterns that used backreferences (\1) or lookaround ((?=...), (?!...), (?<=...)): RE2 has neither (that is what keeps it linear), so they are now refused with invalid_pattern. Rewrite them, or filter in your own code.
  • A view or policy row predicate stored before 2.20.0 with a pattern RE2 cannot compile is NOT refused at read time (it was set by an administrator, and refusing would break every read of the view): it matches nothing, as an invalid pattern always did. Recreate such a view.
  • To search for user input literally, escape it before putting it in a pattern (a backslash before each of .^$|()[]{}*+?\), and add (?i) for a case-insensitive search box.

Note: the old _search magic field name that auto-selected SEARCH is no longer special — use FilterOp::SEARCH explicitly instead.

Collection Management

// Create a basic collection
db.createCollection("users");

// Create with options
db.createCollection("sessions",
    /*defaultTtlSeconds=*/3600,    // auto-expire after 1 hour
    /*encrypted=*/false,
    /*maxVersions=*/5,             // keep last 5 versions
    /*vectorDimension=*/0);        // no vector support

// Create vector-enabled collection
db.createCollection("memories",
    /*defaultTtlSeconds=*/0,
    /*encrypted=*/false,
    /*maxVersions=*/0,
    /*vectorDimension=*/384);      // 384-dim embeddings

// List and inspect
auto collections = db.listCollections();
auto info = db.getCollectionInfo("users");
if (info) {
    std::cout << "Documents: " << info->documentCount << std::endl;
}

// Drop
db.dropCollection("old_data");

Collections and projects (2.4.5+)

Collection names are namespaced with the client's Config::project, exactly like documents. You keep passing bare names; the client qualifies them on the wire and un-qualifies them coming back, so listCollections() round-trips:

Client::Config cfg;
cfg.project = "acme";
Client db(cfg);

db.createCollection("users");              // -> acme:users
db.insert("users", {{"name", "Ada"}});     // -> acme:users
auto info = db.getCollectionInfo("users"); // -> acme:users
db.listCollections();                      // -> { "users", ... }

Fixed in 2.4.5 — upgrade if you call createCollection. On 2.3.0-2.4.4 createCollection, dropCollection and getCollectionInfo sent the bare name while insert/get/find sent the project-qualified one. Because the client qualifies against Config::project unconditionally — including default — every project was affected. One createCollection("things") plus one insert("things") created two collections: the bare one received the options and stayed empty, while <project>:things was created implicitly by the insert with defaults. No error was raised.

Concretely, on affected versions:

  • vectorDimension never reached the collection holding the data, so similaritySearch() returned no hits.
  • encrypted = true silently did not apply.
  • dropCollection() returned true while every document remained readable — it dropped the empty phantom.

After upgrading: leftover empty phantom collections are harmless litter, but options that were swallowed do not retroactively apply. createCollection on a now-correctly-resolved existing collection returns false and only updates maxVersions (and, since 2.17.1, prunes history to a lower cap). Since vectorDimension is immutable after creation, a collection that needs vector search must be recreated: create a new collection with the right vectorDimension, copy the documents across, then drop the old one.

Note that listCollections() currently returns every project's collections — names outside your own project stay visibly qualified rather than being flattened into yours. Unlike ListViewsRequest, ListCollectionsRequest has no project filter yet.

Vector Similarity Search

Requires a collection created with vectorDimension > 0.

// Insert documents with embeddings
nlohmann::json doc = {
    {"id", "mem-1"},
    {"content", "The user prefers dark mode"},
    {"_vector", embedding}   // std::vector<float>, size must match vectorDimension
};
db.insert("memories", doc, "mem-1");

// Search
std::vector<float> queryVec = getEmbedding("user preferences");
auto results = db.similaritySearch("memories", queryVec, /*topK=*/5, /*minScore=*/0.7f);

for (const auto& r : results) {
    std::cout << r.id << " (score=" << r.score << "): "
              << r.data["content"] << std::endl;
}

Notes:

  • _vector is extracted and stored separately; get()/find() return it only when asked (Client::WithVector, 2.13.0+)
  • Dimension is validated on every insert — mismatches are rejected
  • SIMD-accelerated (AVX2/SSE4.1) brute-force cosine similarity
  • minScore 0.0 drops rows whose cosine is NEGATIVE. It is a threshold, not "no threshold". To rank every row, pass -1.0f.
  • Ties (2.14.0+): rows with equal scores are ordered by id, lower first, and when ties straddle the topK cut the lower ids are kept. Before 2.14.0 the order of tied rows was unspecified.

Filtered similarity search (2.14.0+)

using F = smartbotic::database::Client::Filter;
auto hits = db.similaritySearch("kb_chunks", queryVec, /*topK=*/500, /*minScore=*/0.0f,
                                {F::eq("departmentKey", "webber")});
  • Exact: the filters select candidate rows BEFORE ranking, so the answer is the true top-K among matching rows - never a filtered slice of an unfiltered top-K, and there is no candidate cap. Scores are bit-identical to an unfiltered search with the same vector.
  • Same grammar and evaluator as find(): every operator, ANDed. A row find() would return with those filters is exactly a row the search may rank. An index on the filtered field is used the same way find() uses it.
  • minScore trims after the filter. Fewer matching rows than topK returns all of them (that pass minScore); a filter matching nothing, or naming a field no row carries, returns empty - neither is an error.
  • A matching row that has no stored vector is not returned.
  • SEARCH ignores its field, here as in find(): it is a case-insensitive substring match over the whole document (id, keys, every string and number). It also needs every document decoded, so it never runs at index speed.
  • Access policy applies as it does to find(): the row predicate is ANDed in, masked columns are removed, a filter on a masked column is refused.
  • ⚠ Against a pre-2.14.0 server the filters would be silently ignored and the answer would be UNFILTERED. The client detects that (the response says whether filters were applied) and throws Client::FailedPrecondition, reason filters_unsupported, instead of returning those rows. An empty filter list is the plain search and works against any server.

Measured on 12,447 rows at dimension 4096 (best of 5, one host): unfiltered top 500 187 ms; a filter matching ~430 rows, top 500: 78 ms unindexed, 51 ms indexed; top 5 indexed: 13 ms; a filter matching 1/7 of rows: ~90 ms; a filter matching nothing: under 1 ms. A filtered search scores only matching rows, so it is cheaper than the unfiltered one, not dearer.

Version History

// Get history
auto history = db.getVersionHistory("users", "user-123", /*limit=*/10);
for (const auto& v : history.versions) {
    std::cout << "v" << v.version << " by " << v.updatedBy
              << " at " << v.timestamp << std::endl;
}

// Get a specific version
auto oldVersion = db.getDocumentVersion("users", "user-123", /*version=*/2);

// Restore to a previous version
uint64_t newVer = db.restoreVersion("users", "user-123", /*version=*/2);

// Restore to a point in time
auto [fromVer, newVersion] = db.restoreToDate("users", "user-123", timestamp);

File Storage

Two-level storage with content-addressed blob deduplication. Identical files are stored once.

Files and projects (2.6.0+)

Files are namespaced by project, like collections. The client fills the project from Config::project on every file call, so you keep passing bare ids:

Client::Config cfg;
cfg.project = "acme";
Client db(cfg);

auto up = db.uploadFile(data, meta);   // owned by project "acme"
db.getFileInfo(up.id);                 // resolves
db.listFiles("document");              // only acme's files

Since 2.21.7 an upload is refused with INVALID_ARGUMENT when its project is not a valid project name (reason invalid_project) or its MIME type has no / (reason invalid_mime_type). Before, such metadata was stored as given: two records on one instance held a file path as their project, so no client could ever address them.

An id belonging to another project is reported as NOT_FOUND, not as "forbidden" — getFileInfo returns nullopt, downloadFile throws, deleteFile returns false, and listFiles omits it. The indistinguishability is deliberate: a distinct "exists but not yours" answer would confirm that a peer project holds that file.

Before 2.6.0, files had no project at all — one shared blob tree, one flat record tree, and no project field on any file RPC. Any client could read, list, or delete any file by id. On upgrade, existing records are stamped with project: "default" automatically (idempotent, logged at INFO with a count). If your consumer used a non-default project and uploaded files, those files are now owned by default and will not be visible to that project — move them by re-uploading under the intended project.

FileRecord gained a project member, which changes the struct size, so consumers must rebuild against 2.6.0 headers.

Names, deletion, limits and memory (2.12.3+)

  • Names are not unique. Two uploads with the same name are two records with two ids. Find a file by name with listFiles("", "", 100, 0, "", name); a consumer that wants name-addressed files must decide what a second upload of the same name means.
  • Deleting one record is always safe. Identical bytes are stored once and reference-counted across every record and project that holds them; deleting a record decrements the count, and the bytes go only with the last reference.
  • Size limit: storage.files.max_file_size_mb (default 500). An upload over it is refused while it streams - the server stops reading at the limit - with ErrorCode::InvalidArgument, FailureDetail::reason == "file_too_large". A type outside storage.files.allowed_types is refused the same way with "mime_type_not_allowed". Before 2.12.3 both arrived as Internal, and an oversized upload was buffered whole on the server before being refused.
  • Memory: file content lives on disk, not in the document store, and does not count against max_memory_mb. A download streams from disk in 64 KB chunks (2.12.3+; before, the whole file was read into memory first). An upload is still held in server memory until it is complete, up to the size limit per concurrent upload (storage.grpc.max_concurrent_file_streams, default 10) - so on a small machine, lower max_file_size_mb. The client side holds the whole file too: uploadFile takes and downloadFile returns a full buffer.
  • dropProject deletes the project's files (2.12.3+). Bytes another project also holds are kept. Before 2.12.3 a dropped project's files survived and were served to a later project of the same name.

Deduplication is per project

result.deduplicated means this project already referenced those bytes. Blob storage still dedups globally, so the disk saving is unchanged, but the flag is scoped deliberately: reporting the global hit would let you upload a candidate file and learn from the flag whether some other project holds it.

// Upload
std::vector<uint8_t> data = readFile("photo.jpg");
smartbotic::database::Client::FileUploadMeta meta;
meta.name = "photo.jpg";
meta.mime_type = "image/jpeg";
meta.file_type = "document";        // "plugin", "document", "generated"
meta.related_id = "conversation-1";
meta.is_public = false;

auto result = db.uploadFile(data, meta);
std::cout << "File ID: " << result.id
          << " Deduplicated: " << result.deduplicated << std::endl;

// Download
auto fileData = db.downloadFile(result.id);

// Get file info
auto fileInfo = db.getFileInfo(result.id);

// List files
auto files = db.listFiles(
    /*file_type=*/"document",
    /*related_id=*/"conversation-1",
    /*limit=*/100, /*offset=*/0,
    /*checksum=*/"",
    /*name=*/"photo.jpg");
// Each FileRecord carries its metadata map. Servers before 2.21.8 sent it
// empty in a listing (getFileInfo always had it): a consumer that must work
// against those fetches getFileInfo for a listed record whose map is empty.

// Delete
db.deleteFile(result.id);

Event Subscription

auto subscription = db.subscribe({"users", "sessions"}, [](
    const std::string& collection,
    const std::string& id,
    const std::string& eventType,
    const std::optional<nlohmann::json>& data) {

    std::cout << eventType << " on " << collection << "/" << id << std::endl;
});

// Unsubscribe by releasing the handle
subscription.reset();

Who caused a change, and avoiding trigger loops (2.12.0+)

subscribeEvents() delivers a Client::Event, which adds the actor - the actor the write or delete carried - plus the server timestamp and node id:

auto sub = db.subscribeEvents({"orders"}, [](const Client::Event& e) {
    // e.collection, e.id, e.eventType, e.data, e.actor, e.timestamp, e.nodeId
});
Event actor is
insert, update, upsert, patch the actor argument of that call; empty if none was given
delete the actor passed to removeAs(); empty for remove()
a document a relation cascade deleted or nulled the actor of the delete that caused the cascade
expire (TTL) always empty: nobody asked for it

A consumer that writes in response to events - a trigger, a function, a sync job - must be able to recognise its own writes, or something that writes to a collection it watches feeds itself forever. Tag every write it makes with an actor it can recognise, deletes included, and check e.actor before reacting:

const std::string me = "sync-job";
db.patch("orders", id, {{"synced", true}}, me);
db.removeAs("orders", staleId, me);         // remove() has no actor parameter

auto sub = db.subscribeEvents({"orders"}, [&](const Client::Event& e) {
    if (e.actor == me) return;                 // our own change: do not react
    // ...
});

Read the actor from the event, not from version history afterwards. History races any later write, a delete leaves the document's previous state there (its updated_by is whoever last wrote it, not who deleted it), and a patch without an actor keeps the previous writer in updated_by while its event correctly reports no actor.

removeAs() is a separate name rather than a remove() overload on purpose: remove(collection, id, someString) already means "write the error into someString", and C++ would pick that for a std::string variable - an actor overload would have compiled and silently sent nothing.

The original subscribe() is unchanged and still works; it simply does not expose the actor.

Set Operations

Redis-compatible set operations on top of documents.

db.setAdd("tags", "user-123", "admin");
db.setAdd("tags", "user-123", "active");

auto members = db.setMembers("tags", "user-123");
bool isAdmin = db.setIsMember("tags", "user-123", "admin");

db.setRemove("tags", "user-123", "active");

Health & Statistics

// Quick health check
if (db.healthCheck()) {
    std::cout << "Database is healthy" << std::endl;
}

// Detailed health
auto health = db.getHealthInfo();
if (health) {
    std::cout << "Uptime: " << health->uptimeMs << "ms"
              << " Docs: " << health->documentCount << std::endl;
}

// Full statistics
auto stats = db.getStats();
if (stats) {
    std::cout << "Memory: " << stats->memoryUsedBytes << " bytes"
              << " Insert avg: " << stats->insertAvgMicros() << " us" << std::endl;
}

Configuration

The server configuration file is at /etc/smartbotic-database/config.json.

Default Configuration

{
  "log_level": "info",
  "storage": {
    "bind_address": "localhost",
    "rpc_port": 9004,
    "node_id": "smartbotic-db",
    "data_directory": "/var/lib/smartbotic-database",
    "memory": {
      "max_memory_mb": 512,
      "eviction_threshold_percent": 80,
      "eviction_target_percent": 60,
      "eviction_check_interval_ms": 5000
    },
    "persistence": {
      "wal_sync_interval_ms": 100,
      "snapshot_interval_sec": 3600,
      "compression": "lz4"
    },
    "encryption": {
      "enabled": true,
      "key_file": "/var/lib/smartbotic-database/storage.key",
      "auto_generate_key": true
    },
    "migrations": {
      "enabled": false,
      "directory": "/etc/smartbotic-database/migrations",
      "auto_apply": false
    },
    "files": {
      "max_file_size_mb": 500,
      "cleanup_orphans_interval_sec": 3600
    },
    "replication": {
      "enabled": false
    }
  }
}

Key Settings

Setting Default Description
bind_address localhost Change to 0.0.0.0 to accept remote connections
rpc_port 9004 gRPC listen port
data_directory /var/lib/smartbotic-database WAL, snapshots, files stored here
memory.max_memory_mb 512 Maximum memory for document cache. Evicts LRU when exceeded
memory.eviction_max_episode_percent 50 (2.4.3+) Ceiling on the share of the resident set one pressure episode may evict. 0 disables. See the drain-cap note below
persistence.snapshot_interval_sec 3600 Full snapshot every N seconds (WAL truncated after)
encryption.enabled true Field-level AES-256-GCM encryption. Key auto-generated on first start
migrations.enabled false Enable to auto-apply JSON migrations on startup
migrations.directory /etc/smartbotic-database/migrations Path to migration JSON files

gRPC Configuration

Under storage.grpc (added in v1.6.2):

Setting Default Purpose
max_receive_message_size_mb 100 Max inbound gRPC message size. Raise for larger file uploads.
max_send_message_size_mb 100 Max outbound gRPC message size.
resource_quota_memory_mb 256 Global memory budget for gRPC inbound buffers across all RPCs combined.
max_concurrent_subscribe_streams 50 Max simultaneous Subscribe event-stream clients. Excess gets RESOURCE_EXHAUSTED.
max_concurrent_file_streams 10 Max simultaneous UploadFile + DownloadFile streams (shared pool).

When a concurrency limit is hit, the server returns RESOURCE_EXHAUSTED immediately and logs WARN with the current / max counts. Clients should retry with backoff.

Drop-in configuration (conf.d)

In addition to /etc/smartbotic-database/config.json, the server loads any *.json files from /etc/smartbotic-database/conf.d/ and deep-merges them into the running config in lexicographic order.

This lets consumer projects (shadowman-cpp, callerai, your own apps) ship their own tuning without touching the upstream config.json that dpkg --configure guards as a conffile.

Merge semantics (RFC 7396)

  • Objects merge recursively: sibling fields not mentioned in a drop-in are preserved from the lower-priority layer.
  • Arrays and scalars are replaced entirely by a higher-priority layer.

Example:

// /etc/smartbotic-database/config.json
{
  "log_level": "info",
  "storage": {
    "rpc_port": 9004,
    "memory": { "max_memory_mb": 512 }
  }
}

// /etc/smartbotic-database/conf.d/50-shadowman.json  (shipped by shadowman-cpp's deb)
{
  "storage": {
    "memory": { "max_memory_mb": 2048 }
  }
}

// Effective merged config — sibling rpc_port preserved, max_memory_mb overridden
{
  "log_level": "info",
  "storage": {
    "rpc_port": 9004,
    "memory": { "max_memory_mb": 2048 }
  }
}

File naming conventions

Use numeric prefixes for deterministic merge order. Last writer wins.

File Owner Purpose
00-defaults.json smartbotic-database (optional) Baseline conservative tunings
50-<project>.json consumer project's deb postinst Workload-tuned values
99-local.json operator Site-specific overrides

Files are merged in filename-sort order, so 00- applies before 50- applies before 99-.

Failure modes

  • Missing base config.json — OK, treated as {}
  • Missing conf.d/ directory — OK
  • Syntax error in any file — server refuses to start, exit code 11, log identifies the file + parser location
  • Unknown keys — lenient. Individual config consumers may log WARN but don't block startup. This lets v1.x consumers drop a conf.d/ file that mentions a key only v1.(x+1) knows about

What gets logged

At startup, the server prints each file as it merges it:

[INFO] Loading base config: /etc/smartbotic-database/config.json
[INFO] Merging drop-in: /etc/smartbotic-database/conf.d/50-shadowman.json
[INFO] Merging drop-in: /etc/smartbotic-database/conf.d/99-local.json

If a consumer wonders which tuning values are actually in effect, this is where to look.

Eviction & Memory Pressure

smartbotic-database holds documents in memory for fast reads. When usage approaches the configured budget (storage.memory.max_memory_mb), eviction removes the least-useful docs to free space. Eviction is chunked, throttled, and hot-write-aware so it doesn't block foreground writes — a design requirement after the 2026-04-22 Zoe incident where one-shot eviction stalled LLM streaming writes long enough to miss their gRPC deadline.

Pressure levels

The server tracks four pressure levels based on current usage vs. max_memory_mb:

Level Default % Behavior
normal < 70% No eviction
soft 70–85% Trickle eviction: one chunk per tick
hard 85–95% Aggressive eviction: up to max_eviction_passes_per_trigger / 2 chunks per tick. Fires MEMORY_PRESSURE_HIGH event (edge-triggered)
emergency ≥ 95% All writes rejected with RESOURCE_EXHAUSTED until pressure drops below hard. Eviction runs at full rate

Pressure refuses writes only. Reads are served from LMDB and are unaffected at every level, so a failing read is never caused by memory pressure: look for an outage or a restart instead.

Query current state via smartbotic-db-cli status or the GetMemoryStats RPC.

Vectors count against the budget (2.21.2+)

A stored vector is part of what memory holds, and from 2.21.2 it is counted and freed like the rest of the document:

  • Counted everywhere it enters memory. Before 2.21.2 a vector loaded at boot (from the snapshot or the WAL) was never added to the estimate, so a vector store reported a fraction of what it held: one production instance read 237 MB estimated (46%) with about 615 MiB of 4096-dimension vectors resident beside it.
  • Released by eviction. Eviction used to remove only the body and leave the vector in memory for the life of the process, so the budget could never reclaim the largest thing in a vector store. Evicting a document now releases its vector too, but only while the LMDB mirror is healthy with zero drift (LMDB then holds the current copy). A write or read that reloads the document reloads the vector from LMDB. Search is served from LMDB as before, so a released vector still ranks.
  • Reported on its own. The periodic memory line reads Memory check: N MB estimated (P%, pressure=...), of which vectors V MB, .... V is the resident vector share of N. Both are MiB (2^20 bytes) although the line says MB; size a budget from them in MiB. The first line is logged within one eviction tick of startup, so it serves as the boot figure.

Before upgrading a vector-heavy instance to 2.21.2, compare the vector share with the budget. At the first boot the estimate rises by every resident vector (about dimension x 4 + 32 bytes each), and a store whose budget was sized from the old figure can boot straight into hard or emergency pressure. At emergency writes are refused with RESOURCE_EXHAUSTED until eviction has released enough vectors. You can avoid that in either of two ways:

  • Raise storage.memory.max_memory_mb (conf.d drop-in) to cover the old estimate plus the vectors before upgrading. Memory use is then unchanged.
  • Keep the budget and let eviction release vectors. Resident memory falls, at the cost of a burst of RESOURCE_EXHAUSTED writes right after the boot, and the drain cap below may pause eviction at soft. The drain takes longer than a typical caller's retry budget (for example 3 attempts 500 ms apart), so callers see exhausted retries, not a short pause. Every write is refused during that time, createCollection included, so bootstrap steps a service runs at startup fail until pressure drops.

Mirrored vectors leave memory (2.21.3+)

While the LMDB mirror is healthy, every read of a vector (similarity search, filtered search, get/find with WithVector, export) is served from LMDB, so the copy MemoryStore kept was a second copy of the same bytes. On a small host the two competed: one production instance (1973 MB RAM) held 616 MiB of vectors in memory while search pulled the same vectors through the page cache, and the first search on a large collection took 1.4-5.1 s reading them from disk while process memory went to swap.

From 2.21.3 the eviction loop drops a vector from memory on every tick (about every 5 s) once LMDB holds a byte-identical copy, whatever the memory pressure:

  • Only while the mirror is healthy with zero drift, and never for a document with a write in flight. A vector LMDB lacks or disagrees with stays in memory (WARN Vector release: N vector(s) kept in memory ...) until the next write to the row.
  • A write reads it back first. Every write path (insert over an id, update, conditional update, upsert, patch, set ops, restore, delete) reads a released vector back from LMDB before it runs, so the write sees the document exactly as before. If LMDB cannot be read, the write fails rather than proceed as if the row had no vector.
  • Nothing a client reads changes. Search, get and export already read LMDB. The snapshot reads released vectors from LMDB. The degraded search (mirror unhealthy) scores released vectors by reading them from LMDB, so it loses no candidates; an LMDB read error there is an error, not a shorter answer.
  • The memory line reads ..., of which vectors V MB (R more in LMDB only), ...: V is what is still in memory, R the number released. At boot the snapshot still loads every vector into memory (the boot peak is unchanged); the first tick releases them.
  • The freed memory goes back to the system only with jemalloc's background purge. The packaged server allocates with jemalloc, and the systemd unit sets MALLOC_CONF=background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:1000. With it, RssAnon falls by the released vectors within seconds (measured: a store with 194 MB of vectors went 367 -> 121 MB). Without it (the binary started by hand or in a container that does not set it), jemalloc purges only on allocation activity, so an idle process keeps the pages: the same store went 371 -> 339 MB and stayed there, while the estimate fell by the full 194 MB. Run the server with the unit's MALLOC_CONF wherever it runs. (The server also calls malloc_trim after a large release; that helps only a build linked against glibc malloc.)

Not changed: the first search on a collection still reads its vectors from disk into the page cache (about rows x dimension x 4 bytes). With the duplicate gone that cache has room to stay.

Which store answered: served_from_memory (2.21.3+)

FindResponse and SimilaritySearchResponse carry served_from_memory (capability served_from_memory): true when MemoryStore answered instead of LMDB, i.e. the mirror is unhealthy or drifted, or the collection is a _ system collection. Every server with the capability always sets it; from an older server false means "cannot say". Read it through the out-parameter overloads (a separate type, so no returned struct changes size):

Client::SearchPath path;
auto hits = db.similaritySearch("kb", vec, 5, 0.0f, filters, path);   // filters may be {}
auto page = db.findWithMetrics("kb", Client::QueryOptions{}, path);
if (!db.serverSupports(Client::Capability::kServedFromMemory)) { /* unknown */ }
else if (path.servedFromMemory) { /* degraded: an operator condition */ }

On a find, memoryMatchCount is not a substitute: it is 0 on the LMDB path but also 0 on a degraded find that matched nothing.

Drain cap (2.4.3+)

Eviction assumes the memory estimate falls as documents leave. When memory is held by something eviction cannot free, that assumption breaks: the target is never reachable, and eviction keeps trimming until the cache is empty. On 2026-08-03 a production instance did exactly this — 5996 of ~5990 documents evicted over 30 minutes while the estimate rose (347 → 358 MB). Every collection then reported 0 docs, which looks indistinguishable from data loss. No data was actually lost; it was all still in LMDB.

Two guards now bound this:

  • Episode cap — one pressure episode may evict at most memory.eviction_max_episode_percent (default 50%) of the resident set it started with, enforced per chunk. An episode re-arms only after pressure has been normal for 3 consecutive ticks.
  • No-progress detector — after 3 consecutive ticks that evict documents without lowering the estimate, eviction pauses until pressure clears.

Both log at ERROR. Hitting either means the memory estimate is wrong, not that the store is oversized — treat it as an alert, raise storage.memory.max_memory_mb, and check what is holding memory. Set eviction_max_episode_percent: 0 to disable the cap (not recommended).

Note for v2.0+. MemoryStore is a cache in front of LMDB; the durable copy lives in <dataDir>/projects/<name>/env/. Eviction draining the cache only becomes visible if the LMDB mirror is also unhealthy, which is what made the above incident look total. Watch for v2.0 mirror failed in the log.

Chunked eviction

Eviction never stops the world. Each tick (default every eviction_check_interval_ms = 5000ms, but reactive to pressure):

  1. Collects candidates — docs whose updatedAt is older than hot_write_floor_ms (30 s default) ago, in non-pinned collections
  2. Sorts by (memory_priority, lastAccessedAt) — low-priority + cold goes first
  3. Applies per-collection budget: no one collection contributes more than (share × 1.5) of a single chunk
  4. Evicts eviction_chunk_size docs (default 1000) in one pass
  5. Sleeps eviction_chunk_pause_ms (default 50 ms)
  6. Repeats up to max_eviction_passes_per_trigger times, stopping early if target reached

Docs being actively written (quiesce) are skipped via an in-flight-write counter — eviction can't land mid-upsert.

Per-collection priority

Use CollectionOptions.memory_priority to bias eviction:

Value Meaning
low Evicted preferentially — cold archive collections
normal (default) Standard LRU weight
high Evicted last — hot operational collections
(pinned=true on CollectionOptions) Never evicted

Set via createCollection or migration:

{
  "type": "create_collection",
  "collection": "messages",
  "options": {
    "memory_priority": "high"
  }
}

Config reference (storage.memory)

Setting Default Meaning
max_memory_mb 512 Memory budget before eviction kicks in
eviction_chunk_size 1000 Docs evicted per chunk
eviction_chunk_pause_ms 50 Sleep between chunks within one tick
max_eviction_passes_per_trigger 20 Safety cap on chunks per tick
hot_write_floor_ms 30000 Docs updated within this window are unevictable
memory_soft_percent 70 Enter soft pressure
memory_hard_percent 85 Enter hard pressure — fires PRESSURE_HIGH event
memory_emergency_percent 95 Enter emergency — admission control rejects writes
eviction_burst_threshold 10000 Fire MEMORY_EVICTION_BURST event if chunk ≥ this
eviction_target_percent 60 Stop evicting once usage drops below this
eviction_check_interval_ms 5000 Wake eviction loop this often

Events

Subscribe to receive memory-related notifications:

Event type When Payload
MEMORY_PRESSURE_HIGH Edge-triggered: pressure enters hard or emergency {pressure_level, pressure_percent, estimated_bytes, max_bytes}
MEMORY_EVICTION_BURST An eviction pass touched ≥ eviction_burst_threshold docs {evicted_docs, bytes_freed, pressure_level}

Both are system-level events (empty collection / id). Subscribers filter by event type.

Client-side retry

The client library (v1.7.0+) automatically retries write RPCs that return transient errors:

Status Retry?
DEADLINE_EXCEEDED ✅
RESOURCE_EXHAUSTED (admission control / concurrency cap) ✅
UNAVAILABLE ✅
All others (INVALID_ARGUMENT, FAILED_PRECONDITION, etc.) ❌ — final

Config under Client::Config:

Field Default Meaning
writeRetries 3 Max retry attempts
writeRetryBackoffMs 100 Initial backoff (exponential: 100 → 200 → 400 …)
writeRetryMaxBackoffMs 5000 Cap on any single backoff
writeRetryJitter 0.25 ± 25% jitter

Writes wrapped: insert, updateIfVersion, upsert, remove, patch. Reads are NOT auto-retried — callers retry at their discretion.

Observability

GetMemoryStats RPC (and Client::getMemoryStats()) returns:

  • Total / max memory bytes, pressure percent + level
  • Per-collection: document_count, estimated_bytes, evicted_stub_count, priority
  • Last eviction: timestamp, docs evicted, bytes freed

    auto s = db.getMemoryStats();
    std::cout << "Memory: " << s.totalMemoryBytes << "/" << s.maxMemoryBytes
          << " (" << s.pressurePercent << "% — " << s.pressureLevel << ")" << std::endl;
    for (const auto& c : s.collections) {
    std::cout << "  " << c.collection << ": " << c.documentCount << " docs, "
              << c.estimatedBytes << " bytes, priority=" << c.priority << std::endl;
    }
    

Also shown in smartbotic-db-cli status output (if the CLI exposes it; otherwise subscribers can consume the events).

Recommended tunings

  • Default (512 MB) — development or small services with ~100 K docs
  • 2 GB — production shadowman-cpp profile:

    // /etc/smartbotic-database/conf.d/50-shadowman.json
    {
    "storage": {
    "memory": {
      "max_memory_mb": 2048,
      "memory_soft_percent": 65,
      "memory_hard_percent": 80,
      "eviction_chunk_size": 500,
      "hot_write_floor_ms": 60000
    }
    }
    }
    
  • 8+ GB large — consider raising eviction_burst_threshold to 50000 so you don't get event spam, and consider hot_write_floor_ms: 120000 if your write paths are slow (e.g. STT-heavy callerai)

Troubleshooting

"Client::insert failed: RESOURCE_EXHAUSTED (memory pressure emergency)" — server is in emergency pressure, client is retrying. If this persists, raise max_memory_mb in a conf.d drop-in or lower memory_emergency_percent.

"Eviction: nothing evictable this pass" — every candidate is either pinned, hot-written, or in-flight. Usually benign; server will re-try next tick. If persistent, consider reducing hot_write_floor_ms or flagging some collections as unpinned/low-priority.

Pressure stays at hard despite quiet writes — check eviction_target_percent; eviction stops when usage drops below this. If you want eviction to drain further during idle, raise max_memory_mb or lower the target.

Memory and disk consistency (storage.consistency, 2.21.0+)

The server holds every document twice: in memory (rebuilt at boot from the newest snapshot plus the WAL) and on disk in LMDB (where reads are served from). Writes check memory. When the two disagree about a row:

  • On disk only: reads find it. Before 2.20.2 every write said not-found and an insert of its id overwrote it; since 2.20.2 a write loads it first.
  • In memory only: writes find it (an insert of its id is AlreadyExists), reads do not.

Every boot runs a read-only key audit that compares the two per collection and logs a WARN line per collection plus a summary. The complete id lists go to <data_directory>/consistency-report.json (rewritten every boot). Then it applies these settings:

{
  "storage": {
    "consistency": {
      "disk_only": "adopt",
      "memory_only": "report"
    }
  }
}
Setting Values Default What it does
disk_only adopt / report / remove adopt adopt loads the rows into memory (reads already see them, so nothing visible changes; they are in the next snapshot again). remove deletes them from disk.
memory_only report / write / remove report write copies the rows to disk (they become readable). remove deletes them from memory, through the ordinary delete path (WAL, history, a DELETE event with actor system:consistency-repair).
memory_newer (2.21.7+) report / write report For the boot version audit: a row present on both sides whose memory copy is NEWER than its disk copy (a write whose disk copy failed long ago). report leaves it; reads show the older disk copy until the next write to the row. write copies memory's version to disk at boot, so reads return it. It makes a write nobody has reviewed authoritative, so it is opt-in per instance; the log line names the collection and the count either way.

report changes nothing; the log line says which setting would do what. An unknown value is treated as report.

  • The settings are instance-wide: they act on every collection of every project the audit compares. To repair one project's rows, write or delete them by id through the ordinary API instead (an upsert or patch of a memory-only row copies it to disk; a delete removes it from both).
  • adopt loads a row unchanged: its _version and _updated_at stay as they were. A disk-only row whose collection exists only on disk (not in memory) cannot be adopted (its options, such as the vector dimension, are unknown) and is reported as "not adoptable".
  • consistency-report.json is overwritten at every boot; copy it before a restart if you want to keep it.

Why memory_only defaults to report: nothing in a row says which side is right. A memory-only row is either a write whose disk copy failed (repair: write) or a delete that reached the disk and not memory (repair: remove). For an API-key collection the second is a revoked key, which write would put back into service. Look at consistency-report.json and decide per row.

Rows whose disk copy is KNOWN to have failed are repaired regardless of these settings. Since 2.21.0 a failed copy is recorded in <data_directory>/mirror-pending.log, and the next boot copies those rows from memory (written if memory has them, deleted from disk if not). For those rows memory is right by construction.

Backups: copy the whole data directory. Before 2.21.0 a snapshot silently left out a document that had stayed evicted across a WAL rotation (its copy was read back from a WAL file the previous snapshot had deleted). Such rows lived only in LMDB (projects/*/env/data.mdb), so a backup of snapshots/ plus wal/ lacked them, and Recovery complete: N docs (which counts memory) still looked right. On 2.21.0 the snapshot reads evicted rows from LMDB, and the first boot's adopt puts the lost rows back into memory and the next snapshot. A backup is still the whole data directory, as the package's pre-upgrade backup already copies it.

Snapshots that stop completing (fixed in 2.21.4). Before 2.21.4, eviction could move a row of a system collection (_collection_meta and the like) out of memory. These rows are not stored in LMDB, so the snapshot could read one back only from the WAL, and after one snapshot deleted that WAL file every later snapshot failed:

[error] Failed to create snapshot: evicted document '_collection_meta/...' could
not be read for the snapshot; snapshot abandoned so the WAL that holds it is kept

Nothing clears it while the process runs. The WAL then grows until the next restart, and the restart has to replay all of it. If you see this line on an older server, plan the upgrade to 2.21.4 rather than a plain restart. Recovery time grows with the WAL; the server logs the WAL size at boot (Recovery input: WAL N MB, ...). On 2.21.4 replay logs its progress (WAL replay: N entries applied) and keeps systemd's start timeout from expiring.

Each WAL file is reported at boot (2.21.4+). One line per file:

WAL file wal-current.log: 127940 applied, 0 already in the snapshot,
0 unreadable (0 checksum, first at byte 0), 0 out of sequence order,
sequences 1316788-1444727, read 79619466 of 79619466 bytes

It is logged as WARN when a file's header is unreadable, an entry is unreadable, sequences go backwards, or fewer bytes were read than the file holds. Before 2.21.4 all of these were skipped without a trace. Report any such WARN.

Missing records show up (2.21.7+). A WAL file can be perfectly readable and still lack records: the 2.21.5 write race dropped 63 whole records from one production file, and every reader reported a complete read. Replay now reports the sequence numbers in a file's range that have no record:

[warning] WAL file wal-...: 63 sequence number(s) in this file's range have no record,
at 46 place(s): writes may have been lost from the WAL before it was durable ...

The LMDB copy is not affected (it got those writes when they happened), and the version audit repairs memory. Report the line anyway: it points at the WAL writer.

A damaged record costs only itself (2.21.6+). Up to 2.21.5 replay stopped at the first record it could not read, so every record behind it in that file was lost. Now the reader skips the damaged bytes, resumes at the next valid record, and says so in the file's line (... 1 unreadable (...; 1 skipped past, 587 bytes)). After a crash mid-write the half-written last record is cut before new writes are appended (WAL: cut a torn tail of N byte(s)).

Memory behind disk after a replay (2.21.4+; use 2.21.5). If a replay applies fewer entries than it should, memory keeps older versions of rows that LMDB has newer copies of. Reads are still right, because they are served from LMDB. A patch/increment is not: it merges into memory's copy, so it writes the old fields back over the newer row. The boot step Boot: memory/disk version audit compares every resident row's _version and _updated_at with LMDB's and reloads from LMDB the rows whose LMDB copy is newer:

[warning] version audit: proj:coll: 3 resident row(s) were older than LMDB's copy,
3 reloaded from LMDB (e.g. id (memory v2 at ..., LMDB v3 at ...); ...)

A row can also be newer in MEMORY: an old LMDB copy that missed a write (before 2.21.0 a failed copy was not recorded). Such rows are left in memory and reported (... are NEWER than LMDB's copy, left in memory). Reads show LMDB's older copy until the next write to the row mirrors memory's version over it. 2.21.4 reloaded those too, replacing the newer copy; 2.21.5 does not. A healthy boot logs version audit: N resident row(s) agree with LMDB. The step reads each resident row once from LMDB: about 1 s per 22,000 rows here, 29 s for 222,000 rows on a 1-vCPU host. It is skipped (WARN) when the LMDB mirror is unhealthy or has drift.

The WAL write race (fixed in 2.21.5). Up to 2.21.4 the WAL's periodic flush could race a write and damage one record. Replay stops at a damaged record, so every record behind it in that file was not applied. A WAL file ...: ... (ended early ...) WARN at boot is the sign; the version audit then repairs memory from LMDB.

Configuring for Your Project

Consumer projects typically enable migrations by configuring the database via their own postinst script:

# Example: in your project's postinst
DB_CONFIG="/etc/smartbotic-database/config.json"
python3 -c "
import json
with open('$DB_CONFIG') as f:
    cfg = json.load(f)
s = cfg['storage']
s['migrations']['enabled'] = True
s['migrations']['directory'] = '/opt/myproject/migrations'
s['migrations']['auto_apply'] = True
with open('$DB_CONFIG', 'w') as f:
    json.dump(cfg, f, indent=2)
"
systemctl restart smartbotic-database

Migrations

Declarative JSON-based schema migrations. Create numbered JSON files in the migrations directory.

Migration File Format

{
  "version": "001",
  "name": "create_users",
  "description": "Create users collection with encryption",
  "operations": [
    {
      "type": "create_collection",
      "collection": "users",
      "options": {
        "encrypted": true,
        "max_versions": 10
      }
    }
  ]
}

Available Operations

Operation Fields Description
create_collection collection, options Create a new collection. Options: encrypted, max_versions, default_ttl_seconds, vector_dimension
put collection, document Insert/upsert a document
delete collection, id Delete a document
delete_where_id_prefix collection, prefix Bulk-delete documents whose ID starts with prefix

Vector-Enabled Collection Migration

{
  "version": "002",
  "name": "create_memories",
  "description": "Create vector-enabled memories collection",
  "operations": [
    {
      "type": "create_collection",
      "collection": "memories",
      "options": {
        "vector_dimension": 384
      }
    }
  ]
}

Note: vector_dimension is immutable after collection creation.


Docker Build Integration

When building your project in Docker for production, install the dev package in your base image instead of compiling the submodule from source.

Dockerfile.base Example

FROM debian:trixie

# Add Smartbotics APT repository
COPY smartbotics-repo.gpg /usr/share/keyrings/
RUN echo "deb [signed-by=/usr/share/keyrings/smartbotics-repo.gpg] \
    https://repository.smartbotics.ai trixie main" \
    > /etc/apt/sources.list.d/smartbotics.list

# Configure authentication
ARG REPO_USER=callerai
ARG REPO_PASS
RUN printf "machine repository.smartbotics.ai\nlogin %s\npassword %s\n" \
    "$REPO_USER" "$REPO_PASS" > /etc/apt/auth.conf.d/smartbotics.conf && \
    chmod 600 /etc/apt/auth.conf.d/smartbotics.conf

# Install client dev package (pulls shared lib as dependency)
RUN apt-get update && apt-get install -y \
    libsmartbotic-db-client-dev \
    && rm -rf /var/lib/apt/lists/*

Then your project's CMake uses find_package(smartbotic-db-client REQUIRED) and links against the pre-built shared library.

Production Dockerfile

Let dpkg-shlibdeps compute the library floor (2.18.1+). The libsmartbotic-db-client package ships a symbols file (/var/lib/dpkg/info/libsmartbotic-db-client.symbols): every exported symbol with the first library version that shipped it. If your package is built with debhelper (${shlibs:Depends}) or you run dpkg-shlibdeps -e <binary> yourself, your binary gets libsmartbotic-db-client (>= X) where X is the LOWEST version that has every symbol it actually uses - not the version you happened to build against. That lets the library be upgraded under you (soname 2 only ever adds symbols; a removed public symbol fails our build) and lets an older library satisfy you when you use nothing newer. The floor is never below 2.8.0, the first release under the stable-struct rule.

If you write Depends by hand, use the version of the newest feature you call, not the version you built against, and declare the server separately:

Depends: smartbotic-database (>= 2.17.0), libsmartbotic-db-client (>= 2.17.0), ...

CLI Administration

Install the CLI tool:

sudo apt install smartbotic-db-cli

The CLI connects to the database via gRPC. It does not require the server installed on the same machine — it can administer a remote instance.

Upgrading the CLI does not drag the shared library along (2.18.1-2+). The CLI is linked against the shared libsmartbotic-db-client (deliberately: it is an independent second user of that library on every host), but its package depends only on the lowest library version that has the symbols it uses, computed at build time - e.g. CLI 2.18.1 needs libsmartbotic-db-client (>= 2.17.0). On a host whose services run against library 2.17.x, installing a newer CLI leaves the library alone. Before 2.18.1-2 the CLI required the library at its own version, so an admin-tool upgrade moved the library under every running service.

# Connect to default (localhost:9004)
smartbotic-db-cli health

# Connect to a remote instance
smartbotic-db-cli --address 192.168.1.50:9004 health

Upgrading from Legacy Packages

If your machine previously had shadowman-database or callerai-storage installed, the new smartbotic-database package handles the transition automatically:

sudo apt install smartbotic-database

What happens:

  1. dpkg sees Conflicts: shadowman-database / callerai-storage
  2. The old package is removed (its prerm stops the old service)
  3. smartbotic-database is installed
  4. The postinst script detects old data/config and migrates:
    • /var/lib/shadowman/data/database/ → /var/lib/smartbotic-database/
    • /etc/shadowman/database.json → /etc/smartbotic-database/config.json (paths updated)
    • Same for callerai paths

The old data directory is preserved (copied, not moved) so rollback is safe.

Rollback

If something goes wrong:

sudo apt remove smartbotic-database
sudo apt install shadowman-database=1.2.0-14   # or callerai-storage=0.5.18-1

Old packages remain in the repository.


Proto File

The raw .proto file is available at:

  • Package: /usr/share/smartbotic-database/proto/database.proto
  • Source: proto/database.proto

This can be used to generate client stubs in other languages (Python, Go, etc.) if needed.