浏览代码

feat: 2.16.0 - optional per-collection JSON Schema, suggested from data

A collection may carry a JSON Schema (a subset; any other keyword is refused
when set, so a schema never looks stricter than what is enforced). Every
write's resulting user body must conform: insert, upsert, update,
updateIfVersion, patch and increment on the merged result, restore, set
operations, batch items. Refusal: INVALID_ARGUMENT, reason
schema_violation, fields = the violating paths; values never echoed.
Sensitive fields are judged by their plaintext.

- Set/replace/remove at any time; existing rows are validated first:
  enforce refuses with up to 10 examples, audit applies and counts. Armed
  under the collection write lock before the scan, so no write slips past.
- GetCollectionSchema reads it back (mode, refusal/audit counters).
- SuggestCollectionSchema infers a schema every scanned row conforms to
  (types, required, additionalProperties false, formats, small enums, never
  for a sensitive field).
- Client: setCollectionSchema / removeCollectionSchema /
  getCollectionSchema / suggestCollectionSchema, gated by capability
  collection_schema (server_unsupported against an older server). CLI
  schema, schema-set, schema-drop, schema-suggest. Patterns use RE2.

Requested by the owner and by smartbotic-vectorapi.

Tests: test_json_schema 89; test_collection_schema 56 + 5 after a restart
(encryption on, ciphertext verified on disk); test_server_info old phase;
compat.sh green against 2.15.0 and 2.14.0. Reverted alone: merged-patch
check 4 fail, decrypt 1, sensitive enum 2, existing-row check 2, boot
arming 1, restore check 2.
fszontagh 1 月之前
父节点
当前提交
1391d14d1b

文件差异内容过多而无法显示
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.15.0
+2.16.0

+ 77 - 0
cli/main.cpp

@@ -23,6 +23,7 @@
 #include <cstdio>
 #include <cstring>
 #include <fstream>
+#include <iterator>
 #include <iostream>
 #include <sstream>
 #include <string>
@@ -77,6 +78,12 @@ void printUsage() {
               << "  " << C_CYAN << "unlock" << C_RESET << "                               Unlock database (accept writes)\n"
               << "  " << C_CYAN << "status" << C_RESET << "                               Show read-only + recovery status\n"
               << "  " << C_CYAN << "server-info" << C_RESET << "                          Server version, commit and feature names (2.15.0+)\n"
+              << C_BOLD << "  Collection schema (v2.16.0+)" << C_RESET << "\n"
+              << "  " << C_CYAN << "schema" << C_RESET << " <collection>                  Show the schema, mode and counters\n"
+              << "  " << C_CYAN << "schema-set" << C_RESET << " <collection> <json|@file> [--audit]\n"
+              << "    " << C_DIM << "existing rows are checked first; enforce refuses if any violates it" << C_RESET << "\n"
+              << "  " << C_CYAN << "schema-drop" << C_RESET << " <collection>             Remove the schema\n"
+              << "  " << C_CYAN << "schema-suggest" << C_RESET << " <collection> [limit]   Suggest a schema from the rows\n"
               << C_BOLD << "  Access policy (v2.7.0+)" << C_RESET << "\n"
               << "  " << C_CYAN << "security" << C_RESET << " [project]                   Show whether a project enforces policy\n"
               << "  " << C_CYAN << "indexes" << C_RESET << " <collection>"
@@ -515,6 +522,76 @@ bool execCommand(smartbotic::database::Client& client,
             return true;
         }
 
+        if (cmd == "schema" || cmd == "schema-drop" || cmd == "schema-suggest") {
+            if (params.empty()) {
+                printError("usage: " + cmd + " <collection>");
+                return false;
+            }
+            if (cmd == "schema") {
+                const auto s = client.getCollectionSchema(params[0]);
+                if (!s) {
+                    std::cout << "no schema on " << params[0] << "\n";
+                    return true;
+                }
+                std::cout << "mode:     " << (s->mode == smartbotic::database::Client::SchemaMode::Audit ? "audit" : "enforce")
+                          << (s->armed ? "" : "  (NOT ARMED: the stored schema does not compile)") << "\n"
+                          << "refusals: " << s->refusals << "   audit violations: " << s->auditViolations
+                          << "   (since armed)\n"
+                          << s->schema.dump(2) << "\n";
+                return true;
+            }
+            if (cmd == "schema-suggest") {
+                const uint64_t limit = params.size() > 1 ? std::stoull(params[1]) : 0;
+                const auto s = client.suggestCollectionSchema(params[0], limit);
+                std::cerr << "scanned " << s.rowsScanned << " row(s)" << (s.complete ? "" : " (a sample)")
+                          << "\n";
+                std::cout << s.schema.dump(2) << "\n";
+                return true;
+            }
+            const auto r = client.removeCollectionSchema(params[0]);
+            if (!r.success) {
+                printError(r.error);
+                return false;
+            }
+            std::cout << C_GREEN << "ok" << C_RESET << " schema removed\n";
+            return true;
+        }
+
+        if (cmd == "schema-set") {
+            if (params.size() < 2) {
+                printError("usage: schema-set <collection> <json|@file> [--audit]");
+                return false;
+            }
+            std::string text = params[1];
+            if (!text.empty() && text[0] == '@') {
+                std::ifstream in(text.substr(1));
+                if (!in) {
+                    printError("cannot read " + text.substr(1));
+                    return false;
+                }
+                text.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
+            }
+            nlohmann::json schema;
+            try {
+                schema = nlohmann::json::parse(text);
+            } catch (const std::exception& e) {
+                printError(std::string("not valid JSON: ") + e.what());
+                return false;
+            }
+            const bool audit = std::find(params.begin(), params.end(), "--audit") != params.end();
+            const auto r = client.setCollectionSchema(params[0], schema,
+                                                      audit ? smartbotic::database::Client::SchemaMode::Audit : smartbotic::database::Client::SchemaMode::Enforce);
+            std::cout << "checked " << r.rowsChecked << " existing row(s), " << r.violatingRows
+                      << " not conforming\n";
+            for (const auto& ex : r.examples) std::cout << "  " << ex.id << ": " << ex.message << "\n";
+            if (!r.success) {
+                printError(r.error + (r.reason.empty() ? "" : " [" + r.reason + "]"));
+                return false;
+            }
+            std::cout << C_GREEN << "ok" << C_RESET << " schema set (" << (audit ? "audit" : "enforce") << ")\n";
+            return true;
+        }
+
         if (cmd == "collections") {
             auto collections = client.listCollections();
             std::cout << C_BOLD << "Collections:" << C_RESET << "\n";

+ 74 - 0
client/include/smartbotic/database/client.hpp

@@ -331,6 +331,7 @@ public:
         static constexpr const char* kFilteredSimilarity = "filtered_similarity";
         static constexpr const char* kServerInfo = "server_info";
         static constexpr const char* kClientVersionHeader = "client_version_header";
+        static constexpr const char* kCollectionSchema = "collection_schema";
     };
 
     struct ServerInfo {
@@ -1196,6 +1197,79 @@ public:
                      uint64_t& rowsIndexed);
     bool dropIndex(const std::string& collection, const std::string& field);
 
+    // ===== Collection schema (v2.16.0) =====
+    //
+    // OPTIONAL per collection: a collection without a schema behaves exactly as
+    // before. With one, every write's resulting document (user fields; not
+    // metadata, not `_vector`) must conform, or the write throws / fails with
+    // reason `schema_violation` and the violating paths in FailureDetail::fields
+    // ("name", "addr.zip", "tags[2]"). The language is a JSON Schema subset -
+    // see docs/integration-guide.md; anything outside it is refused when set
+    // (reason `invalid_schema`). All four methods need a 2.16.0 server and
+    // refuse otherwise (FailedPrecondition, reason `server_unsupported`).
+
+    enum class SchemaMode { Enforce, Audit };
+
+    struct SchemaRowViolation {
+        std::string id;
+        std::string message;
+        std::vector<std::string> fields;
+    };
+
+    struct SchemaChangeResult {
+        bool success = false;
+        std::string error;
+        std::string reason;          // e.g. invalid_schema, server_unsupported; "" if in-band
+        uint64_t rowsChecked = 0;    // existing rows validated against the new schema
+        uint64_t violatingRows = 0;
+        std::vector<SchemaRowViolation> examples;   // up to 10
+    };
+
+    struct CollectionSchema {
+        nlohmann::json schema;       // as it was set
+        SchemaMode mode = SchemaMode::Enforce;
+        uint64_t auditViolations = 0;   // audit: non-conforming writes let through since armed
+        uint64_t refusals = 0;          // enforce: writes refused since armed
+        bool armed = true;              // false only if the stored schema no longer compiles
+    };
+
+    struct SchemaSuggestion {
+        nlohmann::json schema;       // every scanned row conforms to it
+        uint64_t rowsScanned = 0;
+        bool complete = false;       // every row was scanned
+    };
+
+    /**
+     * Set or replace the collection's schema (any time; the collection may
+     * already hold data). Every EXISTING row is validated first: in Enforce
+     * mode one violating row refuses the change (success=false, the count and
+     * up to 10 examples); in Audit mode the schema is applied regardless and
+     * the same counts are reported, and later non-conforming writes are logged
+     * and counted instead of refused. To declare a schema "at creation", call
+     * this right after createCollection(): any row written in between is
+     * validated by the same existing-row check.
+     */
+    [[nodiscard]] SchemaChangeResult setCollectionSchema(const std::string& collection,
+                                                         const nlohmann::json& schema,
+                                                         SchemaMode mode = SchemaMode::Enforce);
+
+    /// Remove the collection's schema; writes are no longer validated.
+    [[nodiscard]] SchemaChangeResult removeCollectionSchema(const std::string& collection);
+
+    /// The schema as set, its mode and counters; nullopt = no schema. Throws
+    /// Client::Error when it cannot be read (the v2.12.4 rule for reads).
+    [[nodiscard]] std::optional<CollectionSchema> getCollectionSchema(const std::string& collection);
+
+    /**
+     * A schema suggested from the collection's rows (all of them, or the first
+     * `sampleLimit`), which every scanned row conforms to: types, required
+     * keys, additionalProperties false, detected formats, small enums. Lengths
+     * and ranges are only described, not enforced - edit before applying.
+     * Throws Client::Error on failure.
+     */
+    [[nodiscard]] SchemaSuggestion suggestCollectionSchema(const std::string& collection,
+                                                           uint64_t sampleLimit = 0);
+
     /**
      * Result of createUniqueIndex() below. A brand-new struct, not a member
      * added to IndexDefinition or CreateIndexResponse's shape - same ABI

+ 102 - 0
client/src/client.cpp

@@ -1752,6 +1752,89 @@ public:
         return out;
     }
 
+    // ===== Collection schema (v2.16.0) =====
+
+    Client::SchemaChangeResult schemaChange(const std::string& collection, const std::string& schemaJson,
+                                            Client::SchemaMode mode) {
+        Client::SchemaChangeResult out;
+        try {
+            requireCapability(Client::Capability::kCollectionSchema, "setCollectionSchema");
+        } catch (const Client::Error& e) {
+            out.error = e.what();
+            if (const auto* d = Client::errorDetail(e)) out.reason = d->reason;
+            return out;
+        }
+        smartbotic::databasepb::SetCollectionSchemaRequest request;
+        request.set_collection(qualify(collection));
+        request.set_schema_json(schemaJson);
+        request.set_mode(mode == Client::SchemaMode::Audit ? "audit" : "enforce");
+        smartbotic::databasepb::SetCollectionSchemaResponse response;
+        grpc::ClientContext context;
+        // The existing-row check scans the collection: give it the export cap,
+        // not a unary deadline.
+        context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
+        attachAuth(context);
+        auto status = stub_->SetCollectionSchema(&context, request, &response);
+        if (!status.ok()) {
+            const auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(),
+                                      trailerDetail(context));
+            out.error = status.error_message();
+            out.reason = d.reason;
+            spdlog::error("Client::setCollectionSchema failed: {}", out.error);
+            return out;
+        }
+        out.success = response.success();
+        out.error = response.error();
+        out.rowsChecked = response.rows_checked();
+        out.violatingRows = response.violating_rows();
+        for (const auto& ex : response.examples()) {
+            out.examples.push_back({ex.id(), ex.message(), {ex.fields().begin(), ex.fields().end()}});
+        }
+        if (!out.success) spdlog::error("Client::setCollectionSchema refused: {}", out.error);
+        return out;
+    }
+
+    std::optional<Client::CollectionSchema> getCollectionSchema(const std::string& collection) {
+        requireCapability(Client::Capability::kCollectionSchema, "getCollectionSchema");
+        smartbotic::databasepb::GetCollectionSchemaRequest request;
+        request.set_collection(qualify(collection));
+        smartbotic::databasepb::GetCollectionSchemaResponse response;
+        grpc::ClientContext context;
+        setDeadline(context);
+        auto status = stub_->GetCollectionSchema(&context, request, &response);
+        if (!status.ok()) {
+            throwStatus(status, "getCollectionSchema: " + status.error_message(), trailerDetail(context));
+        }
+        if (!response.has_schema()) return std::nullopt;
+        Client::CollectionSchema out;
+        out.schema = nlohmann::json::parse(response.schema_json());
+        out.mode = response.mode() == "audit" ? Client::SchemaMode::Audit : Client::SchemaMode::Enforce;
+        out.auditViolations = response.audit_violations();
+        out.refusals = response.refusals();
+        out.armed = response.armed();
+        return out;
+    }
+
+    Client::SchemaSuggestion suggestCollectionSchema(const std::string& collection, uint64_t sampleLimit) {
+        requireCapability(Client::Capability::kCollectionSchema, "suggestCollectionSchema");
+        smartbotic::databasepb::SuggestCollectionSchemaRequest request;
+        request.set_collection(qualify(collection));
+        request.set_sample_limit(sampleLimit);
+        smartbotic::databasepb::SuggestCollectionSchemaResponse response;
+        grpc::ClientContext context;
+        context.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(600));
+        attachAuth(context);
+        auto status = stub_->SuggestCollectionSchema(&context, request, &response);
+        if (!status.ok()) {
+            throwStatus(status, "suggestCollectionSchema: " + status.error_message(), trailerDetail(context));
+        }
+        Client::SchemaSuggestion out;
+        out.schema = nlohmann::json::parse(response.schema_json());
+        out.rowsScanned = response.rows_scanned();
+        out.complete = response.complete();
+        return out;
+    }
+
     std::vector<Client::IndexDefinition> listIndexes(const std::string& collection,
                                                       std::vector<bool>* uniqueFlags) {
         smartbotic::databasepb::ListIndexesRequest request;
@@ -3558,6 +3641,25 @@ Client::FileListResult Client::listFiles(const std::string& file_type,
 #define SMARTBOTIC_DB_GIT_COMMIT_STRING "unknown"
 #endif
 
+Client::SchemaChangeResult Client::setCollectionSchema(const std::string& collection,
+                                                       const nlohmann::json& schema,
+                                                       SchemaMode mode) {
+    return impl_->schemaChange(collection, schema.dump(), mode);
+}
+
+Client::SchemaChangeResult Client::removeCollectionSchema(const std::string& collection) {
+    return impl_->schemaChange(collection, "", SchemaMode::Enforce);
+}
+
+std::optional<Client::CollectionSchema> Client::getCollectionSchema(const std::string& collection) {
+    return impl_->getCollectionSchema(collection);
+}
+
+Client::SchemaSuggestion Client::suggestCollectionSchema(const std::string& collection,
+                                                         uint64_t sampleLimit) {
+    return impl_->suggestCollectionSchema(collection, sampleLimit);
+}
+
 std::optional<Client::ServerInfo> Client::serverInfo(bool refresh) {
     return impl_->serverInfo(refresh);
 }

+ 12 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Released version: 2.15.0** (see `VERSION`). Last reviewed: 2026-10-09.
+**Released version: 2.16.0** (see `VERSION`). Last reviewed: 2026-10-09.
 
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
@@ -56,12 +56,14 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.15.0. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.16.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
 - LMDB storage substrate, one env per project, dual-write mirror from MemoryStore
 - Multi-project namespaces (`<project>:<collection>`)
+- Optional per-collection JSON Schema (enforce/audit, existing rows checked
+  first, suggested from data) (2.16.0)
 - Independent client and server releases: `GetServerInfo` capability
   negotiation, decoupled packages, `build.sh --only`, `packaging/compat.sh` (2.15.0)
 - Vector storage with SIMD cosine similarity search; filtered search, exact
@@ -469,6 +471,14 @@ joins; see 5c), which does not fit in 10 s. The container is now run with
   comparison.
 - TTL is not retro-applied: rows written before a default TTL existed keep no
   expiry.
+- **Top-level sensitive fields are not encrypted (found 2026-10-09).** The
+  built-in patterns (`*.password`, `*.api_key`, `*.token`, ...) become regexes
+  that need a dot before the name, so only NESTED fields match; a top-level
+  `password` is stored in plaintext. The patterns are not configurable. Fixing
+  it changes what gets encrypted on existing installs (rows written before stay
+  plaintext until rewritten), so it wants its own release and a migration note.
+- Collection schemas cannot be declared in a migration file yet (the
+  existing-row check lives in the SetCollectionSchema handler).
 - ~~**Bogus index declarations on zeus (found 2026-10-09, predates 2.14.0):**~~ removed
   the same day; kept for the record.
   `smartbotic-automation` holds two declarations on collections literally named

+ 73 - 0
docs/integration-guide.md

@@ -585,6 +585,79 @@ auto now = db.increment("stats", "2026-10-07", {{"calls", 1}, {"minutes", 3.5},
   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.
+
+```cpp
+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.
+
+**⚠ A sensitive-field caveat, independent of schemas:** the default sensitive-field patterns (`*.password`, `*.api_key`, ...) need a dot before the name, so they match a NESTED field only. A top-level `password` is stored in plaintext. The patterns are built in (not configurable), so nest secrets, e.g. `creds.password`. Found while testing 2.16.0; recorded in the ROADMAP.
+
 ### Indexes and unique constraints
 
 ```cpp

+ 1 - 1
packaging/deb/templates/control.server

@@ -14,5 +14,5 @@ License: proprietary
 Provides: shadowman-database, callerai-storage
 Conflicts: shadowman-database, callerai-storage
 Replaces: shadowman-database, callerai-storage
-Depends: adduser, libprotobuf32t64, libgrpc++1.51t64, libspdlog1.15, libfmt10, libssl3t64, liblz4-1, libsystemd0, libjemalloc2, libyyjson0, liblmdb0
+Depends: adduser, libprotobuf32t64, libgrpc++1.51t64, libre2-11, libspdlog1.15, libfmt10, libssl3t64, liblz4-1, libsystemd0, libjemalloc2, libyyjson0, liblmdb0
 Installed-Size: {{INSTALLED_SIZE}}

+ 64 - 0
proto/database.proto

@@ -136,6 +136,11 @@ service DatabaseService {
     // ones (a low-cardinality field like a status enum is slower through an
     // index than a scan).
     rpc CreateIndex(CreateIndexRequest) returns (CreateIndexResponse);
+    // v2.16.0 - per-collection JSON Schema: every write's resulting document
+    // must conform (enforce) or is logged and counted (audit).
+    rpc SetCollectionSchema(SetCollectionSchemaRequest) returns (SetCollectionSchemaResponse);
+    rpc GetCollectionSchema(GetCollectionSchemaRequest) returns (GetCollectionSchemaResponse);
+    rpc SuggestCollectionSchema(SuggestCollectionSchemaRequest) returns (SuggestCollectionSchemaResponse);
     rpc DropIndex(DropIndexRequest) returns (DropIndexResponse);
     rpc ListIndexes(ListIndexesRequest) returns (ListIndexesResponse);
     // v2.10.0 — the distinct values an indexed field holds, with row counts.
@@ -1321,6 +1326,65 @@ message ConfigureCollectionResponse {
 }
 
 // v2.9.0 — secondary index management.
+// ===== Collection schema (v2.16.0) =====
+//
+// The schema language is a JSON Schema subset; any keyword outside it is
+// refused (INVALID_ARGUMENT, reason `invalid_schema`) so a schema never looks
+// stricter than what is enforced. See service/src/schema/json_schema.hpp.
+// A refused WRITE answers INVALID_ARGUMENT, reason `schema_violation`, with the
+// violating fields in the detail's `fields`.
+
+message SetCollectionSchemaRequest {
+    string collection = 1;
+    string schema_json = 2;   // empty = remove the collection's schema
+    string mode = 3;          // "enforce" (default) or "audit"
+}
+
+// One existing row that does not conform.
+message SchemaRowViolation {
+    string id = 1;
+    string message = 2;
+    repeated string fields = 3;
+}
+
+message SetCollectionSchemaResponse {
+    // false = not applied: `error` says why. In enforce mode a schema that any
+    // existing row violates is refused, with up to 10 `examples`; in audit
+    // mode it is applied and the same counts are reported.
+    bool success = 1;
+    string error = 2;
+    uint64 rows_checked = 3;
+    uint64 violating_rows = 4;
+    repeated SchemaRowViolation examples = 5;
+}
+
+message GetCollectionSchemaRequest {
+    string collection = 1;
+}
+
+message GetCollectionSchemaResponse {
+    bool has_schema = 1;
+    string schema_json = 2;      // as it was set
+    string mode = 3;             // "enforce" | "audit"
+    uint64 audit_violations = 4; // audit mode: non-conforming writes let through, since the schema was armed
+    uint64 refusals = 5;         // enforce mode: writes refused, since the schema was armed
+    bool armed = 6;              // false only if the stored schema no longer compiles (logged at boot)
+}
+
+message SuggestCollectionSchemaRequest {
+    string collection = 1;
+    uint64 sample_limit = 2;     // 0 = every row
+}
+
+message SuggestCollectionSchemaResponse {
+    // A schema every scanned row conforms to: see SchemaSuggester in
+    // service/src/schema/json_schema.hpp for what it infers and what it
+    // deliberately only reports.
+    string schema_json = 1;
+    uint64 rows_scanned = 2;
+    bool complete = 3;           // every row was scanned (no sample_limit cut)
+}
+
 message CreateIndexRequest {
     // Project-qualified collection name, as every other collection-carrying
     // request takes.

+ 8 - 0
service/CMakeLists.txt

@@ -76,6 +76,7 @@ set(DATABASE_SERVICE_SOURCES
     src/auth/auth_interceptor.cpp
     src/auth/principal.cpp
     src/security/policy_manager.cpp
+    src/schema/json_schema.cpp
 )
 
 # Create executable
@@ -129,6 +130,13 @@ endif()
 target_link_libraries(smartbotic-database PRIVATE ${yyjson_LIBRARIES})
 target_include_directories(smartbotic-database PRIVATE ${yyjson_INCLUDE_DIRS})
 
+# RE2 - v2.16.0 collection schema `pattern` (linear time; std::regex is not
+# safe on caller-supplied strings). Already a gRPC dependency on every target.
+find_path(RE2_INCLUDE_DIR re2/re2.h REQUIRED)
+find_library(RE2_LIBRARY re2 REQUIRED)
+target_link_libraries(smartbotic-database PRIVATE ${RE2_LIBRARY})
+target_include_directories(smartbotic-database PRIVATE ${RE2_INCLUDE_DIR})
+
 # LMDB — v2.0 storage substrate
 target_link_libraries(smartbotic-database PRIVATE ${LMDB_LIBRARY})
 target_include_directories(smartbotic-database PRIVATE ${LMDB_INCLUDE_DIR})

+ 13 - 1
service/src/config/collection_config_manager.cpp

@@ -11,7 +11,7 @@ namespace smartbotic::database {
 namespace {
 
 nlohmann::json toJson(const CollectionCfg& cfg) {
-    return {
+    nlohmann::json j = {
         {"timestamp_precision", cfg.timestampPrecision},
         {"versioning_enabled", cfg.versioningEnabled},
         {"indexed_fields", cfg.indexedFields},
@@ -19,6 +19,13 @@ nlohmann::json toJson(const CollectionCfg& cfg) {
         {"unique_fields", cfg.uniqueFields},
         {"composite_uniques", cfg.compositeUniques}
     };
+    // v2.16.0 - written only when set, so a record without a schema stays
+    // byte-identical to what older binaries write and read.
+    if (cfg.schema) {
+        j["schema"] = *cfg.schema;
+        j["schema_mode"] = cfg.schemaMode;
+    }
+    return j;
 }
 
 CollectionCfg fromJson(const nlohmann::json& j) {
@@ -37,6 +44,11 @@ CollectionCfg fromJson(const nlohmann::json& j) {
     c.uniqueFields = j.value("unique_fields", std::vector<std::string>{});
     // v2.12.0 - absent on every older record: no composite constraints.
     c.compositeUniques = j.value("composite_uniques", std::vector<std::vector<std::string>>{});
+    // v2.16.0 - absent on every older record: no schema.
+    if (auto it = j.find("schema"); it != j.end() && it->is_object()) {
+        c.schema = *it;
+        c.schemaMode = j.value("schema_mode", std::string("enforce"));
+    }
     return c;
 }
 

+ 13 - 1
service/src/config/collection_config_manager.hpp

@@ -7,6 +7,8 @@
 #include <unordered_map>
 #include <vector>
 
+#include <nlohmann/json.hpp>
+
 namespace smartbotic::database {
 
 class MemoryStore;
@@ -87,6 +89,14 @@ struct CollectionCfg {
     // Armed at boot by applyIndexDeclarations(); a declared constraint whose
     // sub-db is absent is rebuilt there.
     std::vector<std::vector<std::string>> compositeUniques;
+
+    // v2.16.0 - the collection's JSON Schema (service/src/schema/json_schema.hpp)
+    // and its mode: "enforce" refuses a non-conforming write, "audit" logs and
+    // counts it and lets it through. Absent = no schema. Lives here for the same
+    // reason as everything above (WAL'd and snapshotted for free); compiled and
+    // armed at boot by DatabaseService::applySchemaDeclarations().
+    std::optional<nlohmann::json> schema;
+    std::string schemaMode = "enforce";
 };
 
 /**
@@ -142,7 +152,7 @@ public:
     // project's document store.
     std::unordered_map<std::string, CollectionCfg> allConfigs() const;
 
-private:
+    // (public since v2.16.0: the schema registry keys by the same form)
     /**
      * v2.11.0 final review (finding 8) — the cache key for a USER collection
      * is its canonical "<project>:<collection>" form, applied on every read
@@ -164,6 +174,8 @@ private:
      */
     static std::string canonicalKey(const std::string& collection);
 
+private:
+
     MemoryStore& store_;
     mutable std::shared_mutex cacheMutex_;
     std::unordered_map<std::string, CollectionCfg> cache_;

+ 264 - 0
service/src/database_grpc_impl.cpp

@@ -1,5 +1,6 @@
 #include "database_grpc_impl.hpp"
 #include "server_capabilities.hpp"
+#include "schema/json_schema.hpp"
 
 #ifndef SMARTBOTIC_DB_VERSION_STRING
 #define SMARTBOTIC_DB_VERSION_STRING "unknown"
@@ -62,6 +63,13 @@ grpc::Status uniqueViolationStatus(grpc::ServerContext* context,
     return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
 }
 
+// v2.16.0 - the write's resulting document breaks its collection's schema.
+// INVALID_ARGUMENT: the caller's data is wrong and retrying cannot help.
+grpc::Status schemaViolationStatus(grpc::ServerContext* context, const SchemaViolation& e) {
+    attachErrorDetail(context, {{"reason", "schema_violation"}, {"fields", e.paths}});
+    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
+}
+
 grpc::Status missingParentStatus(grpc::ServerContext* context,
                                  const smartbotic::db::storage::MissingParentReference& e) {
     attachErrorDetail(context, {{"reason", "missing_parent"},
@@ -491,6 +499,8 @@ grpc::Status DatabaseGrpcImpl::Insert(
         attachErrorDetail(context, {{"reason", "duplicate_id"},
                                     {"conflicting_id", e.id}});
         return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — a duplicate is the caller's mistake, not a server
         // fault. MemoryStore has already undone its own mutation by the
@@ -710,6 +720,8 @@ grpc::Status DatabaseGrpcImpl::Update(
     } catch (const nlohmann::json::exception& e) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                            "Invalid JSON: " + std::string(e.what()));
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — see the Insert handler's note.
         return uniqueViolationStatus(context, e);
@@ -822,6 +834,8 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
     } catch (const nlohmann::json::exception& e) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                            "Invalid JSON: " + std::string(e.what()));
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — see the Insert handler's note.
         return uniqueViolationStatus(context, e);
@@ -928,6 +942,8 @@ grpc::Status DatabaseGrpcImpl::Upsert(
     } catch (const nlohmann::json::exception& e) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
                            "Invalid JSON: " + std::string(e.what()));
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — see the Insert handler's note.
         return uniqueViolationStatus(context, e);
@@ -1234,6 +1250,8 @@ grpc::Status DatabaseGrpcImpl::RestoreVersion(
         response->set_new_version(newVersion);
         response->set_success(true);
         return grpc::Status::OK;
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
@@ -1282,6 +1300,8 @@ grpc::Status DatabaseGrpcImpl::RestoreToDate(
         response->set_new_version(newVersion);
         response->set_success(true);
         return grpc::Status::OK;
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
@@ -2181,6 +2201,8 @@ grpc::Status DatabaseGrpcImpl::SetAdd(
         bool added = store_.setAdd(request->collection(), request->set_id(), request->member());
         response->set_added(added);
         return grpc::Status::OK;
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
@@ -2214,6 +2236,8 @@ grpc::Status DatabaseGrpcImpl::SetRemove(
         bool removed = store_.setRemove(request->collection(), request->set_id(), request->member());
         response->set_removed(removed);
         return grpc::Status::OK;
+    } catch (const SchemaViolation& e) {   // v2.16.0
+        return schemaViolationStatus(context, e);
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
@@ -5069,4 +5093,244 @@ grpc::Status DatabaseGrpcImpl::GetReadOnlyStatus(
     return grpc::Status::OK;
 }
 
+
+// ===== Collection schema (v2.16.0) =====
+
+grpc::Status DatabaseGrpcImpl::SetCollectionSchema(
+    grpc::ServerContext* context,
+    const pb::SetCollectionSchemaRequest* request,
+    pb::SetCollectionSchemaResponse* response
+) {
+    // Changes write behaviour, so it gates as a write (as CreateIndex does).
+    smartbotic::database::Decision dec;
+    if (auto st = gate(context, request->collection(),
+                       smartbotic::database::Access::Write, dec); !st.ok()) {
+        return st;
+    }
+    const std::string& collection = request->collection();
+    if (collection.empty() || collection[0] == '_') {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                            "a schema can only be set on a user collection");
+    }
+    if (service_.isReadOnly()) {
+        response->set_success(false);
+        response->set_error("database is in read-only mode: " + service_.readOnlyReason());
+        return grpc::Status::OK;
+    }
+    const std::string mode = request->mode().empty() ? "enforce" : request->mode();
+    if (mode != "enforce" && mode != "audit") {
+        attachErrorDetail(context, {{"reason", "invalid_schema"}});
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                            "mode must be 'enforce' or 'audit', not '" + mode + "'");
+    }
+    const std::string key = CollectionConfigManager::canonicalKey(collection);
+    auto& registry = service_.schemaRegistry();
+
+    try {
+        // ---- remove ----
+        if (request->schema_json().empty()) {
+            CollectionCfg cfg = config_manager_.configFor(collection);
+            const bool had = cfg.schema.has_value();
+            cfg.schema.reset();
+            cfg.schemaMode = "enforce";
+            std::string err;
+            if (had && !config_manager_.setConfig(collection, cfg, err)) {
+                response->set_success(false);
+                response->set_error("could not store the change: " + err);
+                return grpc::Status::OK;
+            }
+            store_.withCollectionWriteLock(collection, [&] { registry.set(key, nullptr); });
+            spdlog::info("v2.16 schema: {} schema removed", key);
+            response->set_success(true);
+            return grpc::Status::OK;
+        }
+
+        // ---- set / replace ----
+        nlohmann::json schema;
+        try {
+            schema = nlohmann::json::parse(request->schema_json());
+        } catch (const std::exception& e) {
+            attachErrorDetail(context, {{"reason", "invalid_schema"}});
+            return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                                std::string("schema is not valid JSON: ") + e.what());
+        }
+        auto compiled = smartbotic::db::schema::compile(schema);
+        if (!compiled.schema) {
+            attachErrorDetail(context, {{"reason", "invalid_schema"}});
+            return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, compiled.error);
+        }
+        // The existing-row check reads LMDB; while the mirror is unhealthy or
+        // has drifted, MemoryStore may hold rows LMDB does not, and a schema
+        // could be accepted over data that violates it (CreateIndex's rule).
+        if (!service_.mirrorHealthy() || service_.mirrorDriftSinceReady() != 0) {
+            response->set_success(false);
+            response->set_error("cannot set a schema while the LMDB mirror is unhealthy or "
+                                "has drifted since startup: the existing-row check reads LMDB");
+            return grpc::Status::OK;
+        }
+        const auto rc = smartbotic::database::resolveCollection(collection);
+        auto* ds = service_.docStore(rc.project);
+        if (ds == nullptr) {
+            response->set_success(false);
+            response->set_error("no storage for project '" + rc.project + "'");
+            return grpc::Status::OK;
+        }
+
+        auto entry = std::make_shared<smartbotic::db::schema::SchemaEntry>();
+        entry->compiled = compiled.schema;
+        entry->source = schema;
+        entry->audit = mode == "audit";
+
+        // Arm FIRST, holding the collection's write lock: every write either
+        // finished before (and is committed, so the scan below sees it) or
+        // starts after (and is checked by the new schema). Scanning first and
+        // arming after would let a write land unchecked in between.
+        std::shared_ptr<smartbotic::db::schema::SchemaEntry> previous;
+        store_.withCollectionWriteLock(collection, [&] { previous = registry.set(key, entry); });
+
+        uint64_t rows = 0, violating = 0;
+        ds->export_scan(rc.collection, "", false, nullptr, [](uint64_t) {},
+            [&](Document&& doc, smartbotic::db::storage::DocumentStore::ExportVectorState,
+                const float*, size_t) -> bool {
+                ++rows;
+                size_t total = 0;
+                auto v = compiled.schema->validate(service_.schemaView(doc.data()), 10, &total);
+                if (!v.empty()) {
+                    ++violating;
+                    if (response->examples_size() < 10) {
+                        auto* ex = response->add_examples();
+                        ex->set_id(doc.id);
+                        ex->set_message(smartbotic::db::schema::summarize(v, total));
+                        for (const auto& x : v) ex->add_fields(x.path);
+                    }
+                }
+                return true;
+            });
+        response->set_rows_checked(rows);
+        response->set_violating_rows(violating);
+
+        if (violating > 0 && !entry->audit) {
+            registry.set(key, previous);
+            response->set_success(false);
+            response->set_error(std::to_string(violating) + " of " + std::to_string(rows) +
+                                " existing row(s) do not conform; fix them, or set the schema "
+                                "in audit mode first");
+            return grpc::Status::OK;
+        }
+
+        CollectionCfg cfg = config_manager_.configFor(collection);
+        cfg.schema = schema;
+        cfg.schemaMode = mode;
+        std::string err;
+        if (!config_manager_.setConfig(collection, cfg, err)) {
+            registry.set(key, previous);
+            response->set_success(false);
+            response->set_error("could not store the schema: " + err);
+            return grpc::Status::OK;
+        }
+        spdlog::info("v2.16 schema: {} schema set ({}), {} existing row(s) checked, {} not conforming",
+                     key, mode, rows, violating);
+        response->set_success(true);
+        return grpc::Status::OK;
+    } catch (const std::invalid_argument& e) {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
+    } catch (const std::exception& e) {
+        return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
+    }
+}
+
+grpc::Status DatabaseGrpcImpl::GetCollectionSchema(
+    grpc::ServerContext* context,
+    const pb::GetCollectionSchemaRequest* request,
+    pb::GetCollectionSchemaResponse* response
+) {
+    // Anyone who may read the collection may read the rules its rows follow.
+    smartbotic::database::Decision dec;
+    if (auto st = gate(context, request->collection(),
+                       smartbotic::database::Access::Read, dec); !st.ok()) {
+        return st;
+    }
+    const CollectionCfg cfg = config_manager_.configFor(request->collection());
+    if (!cfg.schema) {
+        response->set_has_schema(false);
+        return grpc::Status::OK;
+    }
+    response->set_has_schema(true);
+    response->set_schema_json(cfg.schema->dump());
+    response->set_mode(cfg.schemaMode);
+    auto entry = service_.schemaRegistry().get(CollectionConfigManager::canonicalKey(request->collection()));
+    response->set_armed(entry != nullptr);
+    if (entry) {
+        response->set_audit_violations(entry->auditViolations.load());
+        response->set_refusals(entry->refusals.load());
+    }
+    return grpc::Status::OK;
+}
+
+grpc::Status DatabaseGrpcImpl::SuggestCollectionSchema(
+    grpc::ServerContext* context,
+    const pb::SuggestCollectionSchemaRequest* request,
+    pb::SuggestCollectionSchemaResponse* response
+) {
+    // A read of the collection's contents (types, lengths, small value sets),
+    // so it gates as a read and sees only what the caller may: the row
+    // predicate selects rows, masked columns are removed before inference.
+    smartbotic::database::Decision dec;
+    if (auto st = gate(context, request->collection(),
+                       smartbotic::database::Access::Read, dec); !st.ok()) {
+        return st;
+    }
+    const std::string& collection = request->collection();
+    if (collection.empty() || collection[0] == '_') {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                            "a schema can only be suggested for a user collection");
+    }
+    if (!service_.mirrorHealthy() || service_.mirrorDriftCount() != 0) {
+        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                            "cannot scan while the LMDB mirror is unhealthy or has drifted");
+    }
+    try {
+        const auto rc = smartbotic::database::resolveCollection(collection);
+        auto* ds = service_.docStore(rc.project);
+        if (ds == nullptr) {
+            return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
+                                "no document store for project '" + rc.project + "'");
+        }
+        std::function<bool(const Document&)> include;
+        if (!dec.row.empty()) {
+            include = [this, &dec](const Document& d) {
+                Document copy = d;
+                encryption_.decryptSensitiveFields(copy);
+                return store_.matchesFilters(copy, dec.row);
+            };
+        }
+        smartbotic::db::schema::SchemaSuggester suggester;
+        // A sensitive field's plaintext values never appear as an enum.
+        suggester.setNoEnumPaths([this](const std::string& path) {
+            return service_.isSensitivePath(path);
+        });
+        const uint64_t limit = request->sample_limit();
+        bool cut = false;
+        ds->export_scan(rc.collection, "", false, include, [](uint64_t) {},
+            [&](Document&& doc, smartbotic::db::storage::DocumentStore::ExportVectorState,
+                const float*, size_t) -> bool {
+                if (limit > 0 && suggester.rows() >= limit) {
+                    cut = true;
+                    return false;
+                }
+                applyMask(doc, dec.mask);
+                suggester.add(service_.schemaView(doc.data()));
+                return true;
+            });
+        response->set_schema_json(suggester.result().dump());
+        response->set_rows_scanned(suggester.rows());
+        response->set_complete(!cut);
+        return grpc::Status::OK;
+    } catch (const std::invalid_argument& e) {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
+    } catch (const std::exception& e) {
+        return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
+    }
+}
+
 } // namespace smartbotic::database

+ 11 - 0
service/src/database_grpc_impl.hpp

@@ -324,6 +324,17 @@ public:
 
     // ===== Collection Config Operations =====
 
+    // v2.16.0 - collection schema.
+    grpc::Status SetCollectionSchema(grpc::ServerContext* context,
+                                     const pb::SetCollectionSchemaRequest* request,
+                                     pb::SetCollectionSchemaResponse* response) override;
+    grpc::Status GetCollectionSchema(grpc::ServerContext* context,
+                                     const pb::GetCollectionSchemaRequest* request,
+                                     pb::GetCollectionSchemaResponse* response) override;
+    grpc::Status SuggestCollectionSchema(grpc::ServerContext* context,
+                                         const pb::SuggestCollectionSchemaRequest* request,
+                                         pb::SuggestCollectionSchemaResponse* response) override;
+
     // v2.9.0 — secondary index management.
     grpc::Status CreateIndex(
         grpc::ServerContext* context,

+ 62 - 0
service/src/database_service.cpp

@@ -222,6 +222,7 @@ bool DatabaseService::initialize() {
         // would be served from a frozen index - stale rows returned as current,
         // with nothing logged.
         applyIndexDeclarations();
+        applySchemaDeclarations();   // v2.16.0
 
         // v2.11.0 final review (finding 4) — THE POST-REPLAY RE-MIRROR PASS
         // RUNS HERE, and the position is load-bearing.
@@ -508,6 +509,40 @@ bool DatabaseService::runMigrations() {
     return ok;
 }
 
+nlohmann::json DatabaseService::schemaView(const nlohmann::json& body) const {
+    nlohmann::json copy = body;
+    if (copy.is_object()) {
+        stripReservedFields(copy);
+        copy.erase("_vector");
+    }
+    encryption_->decryptTree(copy);
+    return copy;
+}
+
+void DatabaseService::applySchemaDeclarations() {
+    size_t armed = 0;
+    for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
+        if (!cfg.schema) continue;
+        auto compiled = smartbotic::db::schema::compile(*cfg.schema);
+        if (!compiled.schema) {
+            // Loud: the record says this collection is constrained and it is
+            // not. Only a hand-edited record can get here (the RPC refuses
+            // anything that does not compile).
+            spdlog::error("v2.16 schema: the schema stored for {} does not compile ({}); "
+                          "it is NOT enforced until it is set again", qualified, compiled.error);
+            continue;
+        }
+        auto entry = std::make_shared<smartbotic::db::schema::SchemaEntry>();
+        entry->compiled = compiled.schema;
+        entry->source = *cfg.schema;
+        entry->audit = cfg.schemaMode == "audit";
+        schemas_.set(qualified, entry);
+        ++armed;
+        spdlog::info("v2.16 schema: {} armed ({})", qualified, entry->audit ? "audit" : "enforce");
+    }
+    if (armed > 0) spdlog::info("v2.16 schema: {} collection schema(s) armed", armed);
+}
+
 void DatabaseService::applyIndexDeclarations() {
     size_t applied = 0;
     for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
@@ -1560,6 +1595,33 @@ void DatabaseService::setupComponents() {
         const size_t send = static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024;
         store_->setMaxDocumentBytes(send > 2 * kReadMargin ? send - kReadMargin : send / 2);
     }
+    // v2.16.0 - collection schemas. The check sees the body as the store holds
+    // it, so it validates a copy: read metadata and `_vector` removed (neither
+    // is a user field), sensitive fields decrypted (a rule about a value must
+    // judge the value, not its ciphertext).
+    store_->setSchemaCheck([this](const std::string& collection, const nlohmann::json& body) {
+        auto entry = schemas_.get(CollectionConfigManager::canonicalKey(collection));
+        if (!entry) return;
+        const nlohmann::json copy = schemaView(body);
+        size_t total = 0;
+        auto violations = entry->compiled->validate(copy, 10, &total);
+        if (violations.empty()) return;
+        const std::string summary = smartbotic::db::schema::summarize(violations, total);
+        if (entry->audit) {
+            // Rate-limited: an audit run on a busy collection must not flood
+            // the log. The counter is exact.
+            const uint64_t n = entry->auditViolations.fetch_add(1) + 1;
+            if (n <= 20 || (n & (n - 1)) == 0) {
+                spdlog::warn("v2.16 schema AUDIT: a write to {} does not conform ({} so far): {}",
+                             collection, n, summary);
+            }
+            return;
+        }
+        entry->refusals.fetch_add(1);
+        std::vector<std::string> paths;
+        for (const auto& v : violations) paths.push_back(v.path);
+        throw SchemaViolation(collection, "schema violation: " + summary, std::move(paths));
+    });
     replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
         *store_, *replication_, *persistence_
     );

+ 20 - 0
service/src/database_service.hpp

@@ -10,6 +10,7 @@
 #include "files/file_manager.hpp"
 #include "replication/replication_manager.hpp"
 #include "migrations/migration_runner.hpp"
+#include "schema/schema_registry.hpp"
 #include "views/view_manager.hpp"
 #include "config/collection_config_manager.hpp"
 #include "security/policy_manager.hpp"
@@ -373,6 +374,24 @@ private:
     // persisted in _collection_meta. Must run at boot, after config load.
     void applyIndexDeclarations();
 
+    // v2.16.0 - compile and arm the collection schemas persisted in
+    // _collection_meta. Runs at boot after config load; a schema that no longer
+    // compiles (a newer binary's keyword read by an older one cannot happen -
+    // records only ever hold schemas this binary accepted - but a hand-edited
+    // record can) is logged and NOT armed.
+    void applySchemaDeclarations();
+
+public:
+    // v2.16.0 - the armed schemas; the gRPC handlers change them.
+    smartbotic::db::schema::SchemaRegistry& schemaRegistry() { return schemas_; }
+    // A stored body as a schema judges it: read metadata and `_vector` removed,
+    // sensitive fields decrypted. A copy; used by the write check, the
+    // existing-row check and the suggester alike, so they cannot disagree.
+    nlohmann::json schemaView(const nlohmann::json& body) const;
+    bool isSensitivePath(const std::string& path) const { return encryption_->isSensitiveField(path); }
+
+private:
+
     // v2.11.0 close-out — MemoryStore::TtlExpiryRelationHook. Decides what the
     // TTL sweeper must do about an expiring parent's children, and PERFORMS the
     // cascade itself when one is required, by calling the ordinary
@@ -443,6 +462,7 @@ private:
     std::unique_ptr<ReplicationManager> replication_;
     std::unique_ptr<ViewManager> view_manager_;
     std::unique_ptr<CollectionConfigManager> config_manager_;
+    smartbotic::db::schema::SchemaRegistry schemas_;   // v2.16.0
     // v2.8.0 — per-project access policy. Owned here so its cache is loaded
     // once, after recovery, alongside ViewManager and CollectionConfigManager.
     std::unique_ptr<PolicyManager> policy_manager_;

+ 6 - 0
service/src/encryption/encryption_manager.cpp

@@ -216,6 +216,12 @@ void EncryptionManager::decryptSensitiveFields(Document& doc) {
     doc.set_data(tree);
 }
 
+void EncryptionManager::decryptTree(nlohmann::json& tree) {
+    if (!isEnabled()) return;
+    std::lock_guard lock(mutex_);
+    decryptJsonField(tree, "", "", "");
+}
+
 void EncryptionManager::decryptSensitiveFields(DocumentVersion& ver,
                                                const std::string& collection,
                                                const std::string& id) {

+ 8 - 0
service/src/encryption/encryption_manager.hpp

@@ -112,6 +112,14 @@ public:
      */
     [[nodiscard]] bool isSensitiveField(const std::string& fieldPath) const;
 
+    /**
+     * v2.16.0 - decrypt every encrypted value in a JSON tree in place (no-op
+     * when encryption is off). For the collection-schema check, which must
+     * judge plaintext - `maxLength` on a sensitive field means the value, not
+     * its ciphertext - and works on a throwaway copy.
+     */
+    void decryptTree(nlohmann::json& tree);
+
 private:
     bool loadKeyFromFile();
     bool loadKeyFromEnv();

+ 29 - 0
service/src/memory_store.cpp

@@ -328,6 +328,13 @@ bool MemoryStore::collectionExists(const std::string& name) const {
 
 // ===== Document CRUD =====
 
+void MemoryStore::withCollectionWriteLock(const std::string& collection,
+                                          const std::function<void()>& fn) {
+    CollectionData* coll = getOrCreateCollection(collection);
+    std::unique_lock<std::shared_mutex> lock(coll->mutex);
+    fn();
+}
+
 std::string MemoryStore::insert(const std::string& collection, Document doc) {
     auto startTime = std::chrono::steady_clock::now();
 
@@ -354,6 +361,7 @@ std::string MemoryStore::insert(const std::string& collection, Document doc) {
     if (coll->documents.find(doc.id) != coll->documents.end()) {
         throw DuplicateDocumentId(collection, doc.id);
     }
+    checkSchema(collection, doc.data());   // v2.16.0 - before any mutation
 
     // Extract vector before storing document (strips _vector from JSON data)
     auto vec = extractVector(*coll, doc);
@@ -516,6 +524,7 @@ bool MemoryStore::update(const std::string& collection, const std::string& id, c
     if (it == coll->documents.end()) {
         return false;
     }
+    checkSchema(collection, doc.data());   // v2.16.0 - before any mutation
 
     // Track memory change (old size)
     uint64_t oldSize = estimateDocumentSize(it->second);
@@ -680,6 +689,7 @@ std::string MemoryStore::upsert(const std::string& collection, Document doc) {
     reloadIfEvicted(collection, doc.id);   // v2.12.1
 
     std::unique_lock<std::shared_mutex> lock(coll->mutex);
+    checkSchema(collection, doc.data());   // v2.16.0 - before any mutation
 
     // Extract vector before storing document (strips _vector from JSON data)
     auto vec = extractVector(*coll, doc);
@@ -1204,6 +1214,7 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
     if (it->second.version != expectedVersion) {
         return false;
     }
+    checkSchema(collection, doc.data());   // v2.16.0 - before any mutation
 
     // Track memory change (old size)
     uint64_t oldSize = estimateDocumentSize(it->second);
@@ -1536,6 +1547,10 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
             return 0;
         }
     }
+    // v2.16.0 - the MERGED body must conform, not just the patch: a patch can
+    // break a rule by removing a required field (null) as easily as by setting
+    // a bad value. Still before anything is mutated.
+    checkSchema(collection, merged);
 
     // Track memory change (old size)
     uint64_t oldSize = estimateDocumentSize(it->second);
@@ -1893,6 +1908,7 @@ bool MemoryStore::setAdd(const std::string& collection, const std::string& setId
         {
             nlohmann::json initial = nlohmann::json::object();
             initial["members"] = nlohmann::json::array({member});
+            checkSchema(collection, initial);   // v2.16.0
             doc.set_data(initial);
         }
         doc.version = 1;
@@ -1945,6 +1961,11 @@ bool MemoryStore::setAdd(const std::string& collection, const std::string& setId
             return false;  // Already exists
         }
     }
+    {   // v2.16.0 - the resulting body, before any mutation
+        nlohmann::json probe = tree;
+        probe["members"].push_back(member);
+        checkSchema(collection, probe);
+    }
 
     // v2.11.0 T11 snapshot for undo, gated per finding 5 - see update().
     const bool wantUndo = needsUndoSnapshot(collection);
@@ -2021,6 +2042,11 @@ bool MemoryStore::setRemove(const std::string& collection, const std::string& se
     if (!found) {
         return false;
     }
+    {   // v2.16.0 - the resulting body, before any mutation
+        nlohmann::json probe = tree;
+        probe["members"] = newMembers;
+        checkSchema(collection, probe);
+    }
 
     // v2.11.0 T11 — snapshot for undo. setRemove only shrinks the "members"
     // array itself, which cannot add an index posting - but it also bumps
@@ -2979,6 +3005,9 @@ uint64_t MemoryStore::restoreToVersion(const std::string& collection, const std:
     auto targetOpt = historyStore_->getAtVersion(collection, id, version);
     if (!targetOpt) return 0;
     const DocumentVersion& targetVer = *targetOpt;
+    // v2.16.0 - a restored body is a write like any other: an old version that
+    // breaks today's schema is refused rather than resurrected.
+    checkSchema(collection, targetVer.data());
 
     auto docIt = coll->documents.find(id);
     bool wasDeleted = (docIt == coll->documents.end());

+ 36 - 0
service/src/memory_store.hpp

@@ -75,6 +75,26 @@ public:
     std::string id;
 };
 
+// v2.16.0 - a write whose resulting document does not conform to its
+// collection's schema (enforce mode). Thrown by the schema check BEFORE the
+// write path mutates anything, so a refused write leaves no trace.
+class SchemaViolation : public std::runtime_error {
+public:
+    SchemaViolation(std::string collection_, const std::string& message,
+                    std::vector<std::string> paths_)
+        : std::runtime_error(message), collection(std::move(collection_)),
+          paths(std::move(paths_)) {}
+    std::string collection;
+    std::vector<std::string> paths;   // the violating fields, e.g. "name", "addr.zip"
+};
+
+// v2.16.0 - checks a write's resulting body (as stored: sensitive fields may
+// be encrypted, `_vector` may be present). Throws SchemaViolation to refuse;
+// returns to accept (no schema, conforming, or audit mode). Installed by
+// DatabaseService; MemoryStore stays independent of the schema module.
+using SchemaCheck = std::function<void(const std::string& collection,
+                                       const nlohmann::json& body)>;
+
 using PersistCallback = std::function<void(const std::string& collection,
                                            const std::string& id,
                                            const std::optional<Document>& doc,
@@ -352,6 +372,18 @@ public:
     // text bytes); a patch whose result exceeds it is refused (TooLarge).
     // 0 = no limit. Set by DatabaseService from the gRPC send limit.
     void setMaxDocumentBytes(size_t bytes) { maxDocumentBytes_.store(bytes); }
+
+    // v2.16.0 - the collection-schema check run by every user write path
+    // (insert, update, updateIfVersion, upsert, patch on the MERGED body,
+    // restore, set operations) under the collection lock, before mutation.
+    // NOT run by loadDocument (WAL replay, replication apply): those replay
+    // writes an origin already accepted. Set once at startup.
+    void setSchemaCheck(SchemaCheck check) { schemaCheck_ = std::move(check); }
+
+    // v2.16.0 - run `fn` holding the collection's write lock, so no write to it
+    // is in flight. Used to arm a schema: a write either finished before (and
+    // is seen by the existing-row check) or starts after (and is checked).
+    void withCollectionWriteLock(const std::string& collection, const std::function<void()>& fn);
     size_t maxDocumentBytes() const { return maxDocumentBytes_.load(); }
 
     /**
@@ -1429,6 +1461,10 @@ private:
     // v2.13.1 - the largest stored body (JSON text) a read can still send back;
     // 0 = no limit. Set by DatabaseService from the gRPC send limit.
     std::atomic<size_t> maxDocumentBytes_{0};
+    SchemaCheck schemaCheck_;   // v2.16.0
+    void checkSchema(const std::string& collection, const nlohmann::json& body) const {
+        if (schemaCheck_) schemaCheck_(collection, body);
+    }
     // v2.11.0 close-out — see setTtlExpiryRelationHook(). Written once at boot
     // (before the expiration thread does anything that consults it) and read
     // from the cleanup thread only.

+ 651 - 0
service/src/schema/json_schema.cpp

@@ -0,0 +1,651 @@
+// v2.16.0 - see json_schema.hpp for the supported subset and why it is a subset.
+
+#include "schema/json_schema.hpp"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdint>
+#include <map>
+#include <optional>
+#include <set>
+
+#include <re2/re2.h>
+
+namespace smartbotic::db::schema {
+
+namespace {
+
+enum TypeBit : uint8_t {
+    kObject = 1, kArray = 2, kString = 4, kInteger = 8, kNumber = 16, kBoolean = 32, kNull = 64,
+};
+
+enum class Format { None, DateTime, Date, Email, Uuid };
+
+}  // namespace
+
+struct Node {
+    bool alwaysFalse = false;            // the boolean schema `false`
+    uint8_t typeMask = 0;                // 0 = any type
+    std::map<std::string, std::shared_ptr<const Node>> properties;
+    std::vector<std::string> required;
+    enum class Extra { Allow, Deny, Schema } extra = Extra::Allow;
+    std::shared_ptr<const Node> extraSchema;
+    std::optional<uint64_t> minProperties, maxProperties;
+    std::optional<uint64_t> minLength, maxLength;
+    std::shared_ptr<RE2> pattern;
+    std::string patternSource;
+    Format format = Format::None;
+    std::optional<nlohmann::json> minimum, maximum, exclusiveMinimum, exclusiveMaximum;
+    std::shared_ptr<const Node> items;
+    std::optional<uint64_t> minItems, maxItems;
+    bool uniqueItems = false;
+    std::optional<nlohmann::json> enumValues;   // an array
+    std::optional<nlohmann::json> constValue;
+};
+
+namespace {
+
+const std::set<std::string>& annotations() {
+    static const std::set<std::string> k = {"$schema", "$id", "$comment", "title", "description",
+                                            "default", "examples", "readOnly", "writeOnly",
+                                            "deprecated"};
+    return k;
+}
+
+const std::set<std::string>& supported() {
+    static const std::set<std::string> k = {
+        "type", "properties", "required", "additionalProperties", "minProperties",
+        "maxProperties", "minLength", "maxLength", "pattern", "format", "minimum", "maximum",
+        "exclusiveMinimum", "exclusiveMaximum", "items", "minItems", "maxItems", "uniqueItems",
+        "enum", "const"};
+    return k;
+}
+
+std::string at(const std::string& path) { return path.empty() ? "the schema root" : "'" + path + "'"; }
+
+struct CompileError {
+    std::string message;
+};
+
+uint64_t nonNegative(const nlohmann::json& v, const std::string& kw, const std::string& path) {
+    if (v.is_number_unsigned()) return v.get<uint64_t>();
+    if (v.is_number_integer() && v.get<int64_t>() >= 0) return static_cast<uint64_t>(v.get<int64_t>());
+    if (v.is_number_float()) {
+        const double d = v.get<double>();
+        if (d >= 0 && std::floor(d) == d && d < 1.8e19) return static_cast<uint64_t>(d);
+    }
+    throw CompileError{"'" + kw + "' at " + at(path) + " must be a non-negative integer"};
+}
+
+uint8_t typeBit(const std::string& t, const std::string& path) {
+    if (t == "object") return kObject;
+    if (t == "array") return kArray;
+    if (t == "string") return kString;
+    if (t == "integer") return kInteger;
+    if (t == "number") return kNumber;
+    if (t == "boolean") return kBoolean;
+    if (t == "null") return kNull;
+    throw CompileError{"unknown type '" + t + "' at " + at(path)};
+}
+
+std::shared_ptr<const Node> compileNode(const nlohmann::json& s, const std::string& path) {
+    auto n = std::make_shared<Node>();
+    if (s.is_boolean()) {
+        n->alwaysFalse = !s.get<bool>();
+        return n;
+    }
+    if (!s.is_object()) {
+        throw CompileError{"a schema must be an object or a boolean, at " + at(path)};
+    }
+    for (const auto& [kw, v] : s.items()) {
+        if (annotations().count(kw)) continue;
+        if (!supported().count(kw)) {
+            throw CompileError{"unsupported keyword '" + kw + "' at " + at(path) +
+                               " (refused so a schema never looks stricter than what is "
+                               "enforced; see the integration guide for the subset)"};
+        }
+        if (kw == "type") {
+            if (v.is_string()) {
+                n->typeMask = typeBit(v.get<std::string>(), path);
+            } else if (v.is_array() && !v.empty()) {
+                for (const auto& t : v) {
+                    if (!t.is_string()) throw CompileError{"'type' entries must be strings, at " + at(path)};
+                    n->typeMask |= typeBit(t.get<std::string>(), path);
+                }
+            } else {
+                throw CompileError{"'type' must be a string or a non-empty array, at " + at(path)};
+            }
+        } else if (kw == "properties") {
+            if (!v.is_object()) throw CompileError{"'properties' must be an object, at " + at(path)};
+            for (const auto& [name, sub] : v.items()) {
+                n->properties[name] = compileNode(sub, path.empty() ? name : path + "." + name);
+            }
+        } else if (kw == "required") {
+            if (!v.is_array()) throw CompileError{"'required' must be an array, at " + at(path)};
+            for (const auto& r : v) {
+                if (!r.is_string()) throw CompileError{"'required' entries must be strings, at " + at(path)};
+                n->required.push_back(r.get<std::string>());
+            }
+        } else if (kw == "additionalProperties") {
+            if (v.is_boolean()) {
+                n->extra = v.get<bool>() ? Node::Extra::Allow : Node::Extra::Deny;
+            } else if (v.is_object()) {
+                n->extra = Node::Extra::Schema;
+                n->extraSchema = compileNode(v, path);
+            } else {
+                throw CompileError{"'additionalProperties' must be a boolean or a schema, at " + at(path)};
+            }
+        } else if (kw == "minProperties") {
+            n->minProperties = nonNegative(v, kw, path);
+        } else if (kw == "maxProperties") {
+            n->maxProperties = nonNegative(v, kw, path);
+        } else if (kw == "minLength") {
+            n->minLength = nonNegative(v, kw, path);
+        } else if (kw == "maxLength") {
+            n->maxLength = nonNegative(v, kw, path);
+        } else if (kw == "pattern") {
+            if (!v.is_string()) throw CompileError{"'pattern' must be a string, at " + at(path)};
+            RE2::Options opt;
+            opt.set_log_errors(false);
+            auto re = std::make_shared<RE2>(v.get<std::string>(), opt);
+            if (!re->ok()) {
+                throw CompileError{"'pattern' at " + at(path) + " is not a valid RE2 pattern: " +
+                                   re->error()};
+            }
+            n->pattern = std::move(re);
+            n->patternSource = v.get<std::string>();
+        } else if (kw == "format") {
+            const std::string f = v.is_string() ? v.get<std::string>() : "";
+            if (f == "date-time") n->format = Format::DateTime;
+            else if (f == "date") n->format = Format::Date;
+            else if (f == "email") n->format = Format::Email;
+            else if (f == "uuid") n->format = Format::Uuid;
+            else throw CompileError{"unsupported format '" + f + "' at " + at(path) +
+                                    " (supported: date-time, date, email, uuid)"};
+        } else if (kw == "minimum" || kw == "maximum" || kw == "exclusiveMinimum" ||
+                   kw == "exclusiveMaximum") {
+            if (!v.is_number()) throw CompileError{"'" + kw + "' must be a number, at " + at(path)};
+            if (kw == "minimum") n->minimum = v;
+            else if (kw == "maximum") n->maximum = v;
+            else if (kw == "exclusiveMinimum") n->exclusiveMinimum = v;
+            else n->exclusiveMaximum = v;
+        } else if (kw == "items") {
+            if (!v.is_object() && !v.is_boolean()) {
+                throw CompileError{"'items' must be one schema (the array form is not supported), at " + at(path)};
+            }
+            n->items = compileNode(v, path + "[]");
+        } else if (kw == "minItems") {
+            n->minItems = nonNegative(v, kw, path);
+        } else if (kw == "maxItems") {
+            n->maxItems = nonNegative(v, kw, path);
+        } else if (kw == "uniqueItems") {
+            if (!v.is_boolean()) throw CompileError{"'uniqueItems' must be a boolean, at " + at(path)};
+            n->uniqueItems = v.get<bool>();
+        } else if (kw == "enum") {
+            if (!v.is_array()) throw CompileError{"'enum' must be an array, at " + at(path)};
+            n->enumValues = v;
+        } else if (kw == "const") {
+            n->constValue = v;
+        }
+    }
+    return n;
+}
+
+// ---------------------------------------------------------------- validation
+
+size_t codePoints(const std::string& s) {
+    size_t n = 0;
+    for (unsigned char c : s) {
+        if ((c & 0xC0) != 0x80) ++n;
+    }
+    return n;
+}
+
+bool isIntegral(const nlohmann::json& v) {
+    if (v.is_number_integer() || v.is_number_unsigned()) return true;
+    if (v.is_number_float()) {
+        const double d = v.get<double>();
+        return std::isfinite(d) && std::floor(d) == d;
+    }
+    return false;
+}
+
+bool typeMatches(uint8_t mask, const nlohmann::json& v) {
+    if (mask == 0) return true;
+    if ((mask & kObject) && v.is_object()) return true;
+    if ((mask & kArray) && v.is_array()) return true;
+    if ((mask & kString) && v.is_string()) return true;
+    if ((mask & kNumber) && v.is_number()) return true;
+    if ((mask & kInteger) && isIntegral(v)) return true;
+    if ((mask & kBoolean) && v.is_boolean()) return true;
+    if ((mask & kNull) && v.is_null()) return true;
+    return false;
+}
+
+std::string typeNames(uint8_t mask) {
+    std::string out;
+    const std::pair<uint8_t, const char*> names[] = {{kObject, "object"}, {kArray, "array"},
+        {kString, "string"}, {kInteger, "integer"}, {kNumber, "number"}, {kBoolean, "boolean"},
+        {kNull, "null"}};
+    for (const auto& [bit, name] : names) {
+        if (mask & bit) out += (out.empty() ? "" : " or ") + std::string(name);
+    }
+    return out;
+}
+
+const char* jsonTypeName(const nlohmann::json& v) {
+    if (v.is_object()) return "an object";
+    if (v.is_array()) return "an array";
+    if (v.is_string()) return "a string";
+    if (v.is_boolean()) return "a boolean";
+    if (v.is_null()) return "null";
+    return isIntegral(v) ? "an integer" : "a number";
+}
+
+// JSON Schema equality: numbers compare by value (1 == 1.0), everything else
+// structurally. nlohmann's == already compares numbers across subtypes.
+bool jsonEqual(const nlohmann::json& a, const nlohmann::json& b) { return a == b; }
+
+bool digits(const std::string& s, size_t from, size_t count) {
+    if (from + count > s.size()) return false;
+    for (size_t i = from; i < from + count; ++i) {
+        if (s[i] < '0' || s[i] > '9') return false;
+    }
+    return true;
+}
+
+int num(const std::string& s, size_t from, size_t count) {
+    return std::stoi(s.substr(from, count));
+}
+
+bool validDate(const std::string& s, size_t at) {   // YYYY-MM-DD at s[at]
+    if (!digits(s, at, 4) || s.size() < at + 10 || s[at + 4] != '-' || !digits(s, at + 5, 2) ||
+        s[at + 7] != '-' || !digits(s, at + 8, 2)) {
+        return false;
+    }
+    const int y = num(s, at, 4), m = num(s, at + 5, 2), d = num(s, at + 8, 2);
+    static const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
+    if (m < 1 || m > 12 || d < 1) return false;
+    const bool leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
+    return d <= days[m - 1] + ((m == 2 && leap) ? 1 : 0);
+}
+
+bool formatOk(Format f, const std::string& s) {
+    switch (f) {
+        case Format::None: return true;
+        case Format::Date: return s.size() == 10 && validDate(s, 0);
+        case Format::DateTime: {
+            // RFC 3339: date "T" hh:mm:ss[.frac] ("Z" / +hh:mm / -hh:mm)
+            if (s.size() < 20 || !validDate(s, 0) || (s[10] != 'T' && s[10] != 't')) return false;
+            if (!digits(s, 11, 2) || s[13] != ':' || !digits(s, 14, 2) || s[16] != ':' ||
+                !digits(s, 17, 2)) {
+                return false;
+            }
+            if (num(s, 11, 2) > 23 || num(s, 14, 2) > 59 || num(s, 17, 2) > 60) return false;
+            size_t i = 19;
+            if (i < s.size() && s[i] == '.') {
+                size_t j = i + 1;
+                while (j < s.size() && s[j] >= '0' && s[j] <= '9') ++j;
+                if (j == i + 1) return false;
+                i = j;
+            }
+            if (i < s.size() && (s[i] == 'Z' || s[i] == 'z')) return i + 1 == s.size();
+            if (i < s.size() && (s[i] == '+' || s[i] == '-')) {
+                return s.size() == i + 6 && digits(s, i + 1, 2) && s[i + 3] == ':' &&
+                       digits(s, i + 4, 2) && num(s, i + 1, 2) <= 23 && num(s, i + 4, 2) <= 59;
+            }
+            return false;
+        }
+        case Format::Email: {
+            const auto atPos = s.find('@');
+            if (atPos == std::string::npos || atPos == 0 || s.find('@', atPos + 1) != std::string::npos) {
+                return false;
+            }
+            const std::string domain = s.substr(atPos + 1);
+            const auto dot = domain.rfind('.');
+            if (dot == std::string::npos || dot == 0 || dot + 1 >= domain.size()) return false;
+            for (unsigned char c : s) {
+                if (c <= ' ' || c == 0x7F) return false;
+            }
+            return true;
+        }
+        case Format::Uuid: {
+            if (s.size() != 36) return false;
+            for (size_t i = 0; i < 36; ++i) {
+                const bool dash = i == 8 || i == 13 || i == 18 || i == 23;
+                if (dash ? s[i] != '-' : !std::isxdigit(static_cast<unsigned char>(s[i]))) return false;
+            }
+            return true;
+        }
+    }
+    return true;
+}
+
+const char* formatName(Format f) {
+    switch (f) {
+        case Format::DateTime: return "date-time";
+        case Format::Date: return "date";
+        case Format::Email: return "email";
+        case Format::Uuid: return "uuid";
+        default: return "";
+    }
+}
+
+std::string shortJson(const nlohmann::json& v) {
+    std::string s = v.dump();
+    if (s.size() > 40) s = s.substr(0, 37) + "...";
+    return s;
+}
+
+struct Walker {
+    size_t max;
+    std::vector<Violation> out;
+    size_t total = 0;
+
+    void add(const std::string& path, const char* kw, std::string msg) {
+        ++total;
+        if (out.size() < max) out.push_back({path, kw, std::move(msg)});
+    }
+
+    void walk(const Node& n, const nlohmann::json& v, const std::string& path) {
+        if (n.alwaysFalse) {
+            add(path, "false", "is not allowed by the schema");
+            return;
+        }
+        if (!typeMatches(n.typeMask, v)) {
+            add(path, "type", std::string("is ") + jsonTypeName(v) + ", expected " + typeNames(n.typeMask));
+            return;   // the remaining keywords would only repeat the type error
+        }
+        if (n.constValue && !jsonEqual(*n.constValue, v)) {
+            add(path, "const", "must equal " + shortJson(*n.constValue));
+        }
+        if (n.enumValues) {
+            bool found = false;
+            for (const auto& e : *n.enumValues) {
+                if (jsonEqual(e, v)) { found = true; break; }
+            }
+            // The value itself is not echoed: it may be a decrypted sensitive
+            // field, and this message reaches the caller and the log.
+            if (!found) add(path, "enum", "is not one of " + shortJson(*n.enumValues));
+        }
+        if (v.is_string()) {
+            const auto& s = v.get_ref<const std::string&>();
+            const size_t len = (n.minLength || n.maxLength) ? codePoints(s) : 0;
+            if (n.maxLength && len > *n.maxLength) {
+                add(path, "maxLength", "is " + std::to_string(len) + " characters, longer than maxLength " +
+                                           std::to_string(*n.maxLength));
+            }
+            if (n.minLength && len < *n.minLength) {
+                add(path, "minLength", "is " + std::to_string(len) + " characters, shorter than minLength " +
+                                           std::to_string(*n.minLength));
+            }
+            if (n.pattern && !RE2::PartialMatch(s, *n.pattern)) {
+                add(path, "pattern", "does not match pattern " + shortJson(n.patternSource));
+            }
+            if (n.format != Format::None && !formatOk(n.format, s)) {
+                add(path, "format", std::string("is not a valid ") + formatName(n.format));
+            }
+        }
+        if (v.is_number()) {
+            if (n.minimum && v < *n.minimum) add(path, "minimum", "is " + v.dump() + ", below minimum " + n.minimum->dump());
+            if (n.maximum && v > *n.maximum) add(path, "maximum", "is " + v.dump() + ", above maximum " + n.maximum->dump());
+            if (n.exclusiveMinimum && !(v > *n.exclusiveMinimum)) {
+                add(path, "exclusiveMinimum", "is " + v.dump() + ", not above " + n.exclusiveMinimum->dump());
+            }
+            if (n.exclusiveMaximum && !(v < *n.exclusiveMaximum)) {
+                add(path, "exclusiveMaximum", "is " + v.dump() + ", not below " + n.exclusiveMaximum->dump());
+            }
+        }
+        if (v.is_array()) {
+            if (n.maxItems && v.size() > *n.maxItems) {
+                add(path, "maxItems", "has " + std::to_string(v.size()) + " items, more than maxItems " +
+                                          std::to_string(*n.maxItems));
+            }
+            if (n.minItems && v.size() < *n.minItems) {
+                add(path, "minItems", "has " + std::to_string(v.size()) + " items, fewer than minItems " +
+                                          std::to_string(*n.minItems));
+            }
+            if (n.uniqueItems && v.size() > 1) {
+                // Sorted copy: O(n log n), not pairwise - an array is caller input.
+                std::vector<nlohmann::json> sorted(v.begin(), v.end());
+                std::sort(sorted.begin(), sorted.end());
+                for (size_t i = 1; i < sorted.size(); ++i) {
+                    if (sorted[i - 1] == sorted[i]) {
+                        add(path, "uniqueItems", "contains " + shortJson(sorted[i]) + " more than once");
+                        break;
+                    }
+                }
+            }
+            if (n.items) {
+                for (size_t i = 0; i < v.size(); ++i) {
+                    walk(*n.items, v[i], path + "[" + std::to_string(i) + "]");
+                }
+            }
+        }
+        if (v.is_object()) {
+            for (const auto& r : n.required) {
+                if (!v.contains(r)) add(path.empty() ? r : path + "." + r, "required", "is required");
+            }
+            if (n.maxProperties && v.size() > *n.maxProperties) {
+                add(path, "maxProperties", "has " + std::to_string(v.size()) + " properties, more than " +
+                                               std::to_string(*n.maxProperties));
+            }
+            if (n.minProperties && v.size() < *n.minProperties) {
+                add(path, "minProperties", "has " + std::to_string(v.size()) + " properties, fewer than " +
+                                               std::to_string(*n.minProperties));
+            }
+            for (const auto& [key, val] : v.items()) {
+                const std::string child = path.empty() ? key : path + "." + key;
+                if (auto it = n.properties.find(key); it != n.properties.end()) {
+                    walk(*it->second, val, child);
+                } else if (n.extra == Node::Extra::Deny) {
+                    add(child, "additionalProperties", "is not a property the schema allows");
+                } else if (n.extra == Node::Extra::Schema) {
+                    walk(*n.extraSchema, val, child);
+                }
+            }
+        }
+    }
+};
+
+}  // namespace
+
+std::vector<Violation> CompiledSchema::validate(const nlohmann::json& document,
+                                                size_t maxViolations, size_t* total) const {
+    Walker w{maxViolations, {}, 0};
+    w.walk(*root_, document, "");
+    if (total) *total = w.total;
+    return std::move(w.out);
+}
+
+CompileResult compile(const nlohmann::json& schema) {
+    CompileResult r;
+    try {
+        if (!schema.is_object()) {
+            r.error = "a collection schema must be a JSON object";
+            return r;
+        }
+        auto root = compileNode(schema, "");
+        if (root->typeMask != 0 && !(root->typeMask & kObject)) {
+            r.error = "the root of a collection schema must accept an object (a document is an object)";
+            return r;
+        }
+        r.schema = std::make_shared<CompiledSchema>(root);
+    } catch (const CompileError& e) {
+        r.error = e.message;
+    } catch (const std::exception& e) {
+        r.error = std::string("invalid schema: ") + e.what();
+    }
+    return r;
+}
+
+std::string summarize(const std::vector<Violation>& violations, size_t total) {
+    std::string out;
+    for (const auto& v : violations) {
+        if (!out.empty()) out += "; ";
+        out += (v.path.empty() ? std::string("the document") : "'" + v.path + "'") + " " + v.message;
+    }
+    if (total > violations.size()) {
+        out += " (and " + std::to_string(total - violations.size()) + " more)";
+    }
+    return out;
+}
+
+// ------------------------------------------------------------ suggestion
+
+struct SchemaSuggester::Inf {
+    uint64_t seen = 0;                 // values observed at this path
+    uint8_t types = 0;                 // TypeBit union (integer kept separate from number)
+    bool allIntegral = true;
+    // object
+    uint64_t objects = 0;
+    std::map<std::string, std::unique_ptr<Inf>> props;
+    // array
+    std::unique_ptr<Inf> items;
+    // string
+    uint64_t strings = 0;
+    size_t minLen = SIZE_MAX, maxLen = 0;
+    std::set<std::string> distinct;
+    bool distinctOverflow = false;
+    bool allDateTime = true, allDate = true, allEmail = true, allUuid = true;
+    // number
+    std::optional<nlohmann::json> minNum, maxNum;
+};
+
+namespace {
+
+constexpr size_t kMaxSuggestDepth = 8;
+constexpr size_t kEnumMax = 10;
+
+void observe(SchemaSuggester::Inf& n, const nlohmann::json& v, size_t depth);
+
+}  // namespace
+
+SchemaSuggester::SchemaSuggester() : root_(std::make_unique<Inf>()) {}
+SchemaSuggester::~SchemaSuggester() = default;
+
+namespace {
+
+void observe(SchemaSuggester::Inf& n, const nlohmann::json& v, size_t depth) {
+    ++n.seen;
+    if (v.is_null()) { n.types |= kNull; return; }
+    if (v.is_boolean()) { n.types |= kBoolean; return; }
+    if (v.is_number()) {
+        n.types |= kNumber;
+        if (!isIntegral(v)) n.allIntegral = false;
+        if (!n.minNum || v < *n.minNum) n.minNum = v;
+        if (!n.maxNum || v > *n.maxNum) n.maxNum = v;
+        return;
+    }
+    if (v.is_string()) {
+        n.types |= kString;
+        ++n.strings;
+        const auto& s = v.get_ref<const std::string&>();
+        const size_t len = codePoints(s);
+        n.minLen = std::min(n.minLen, len);
+        n.maxLen = std::max(n.maxLen, len);
+        if (!n.distinctOverflow) {
+            n.distinct.insert(s);
+            if (n.distinct.size() > kEnumMax) { n.distinctOverflow = true; n.distinct.clear(); }
+        }
+        if (n.allDateTime && !formatOk(Format::DateTime, s)) n.allDateTime = false;
+        if (n.allDate && !formatOk(Format::Date, s)) n.allDate = false;
+        if (n.allEmail && !formatOk(Format::Email, s)) n.allEmail = false;
+        if (n.allUuid && !formatOk(Format::Uuid, s)) n.allUuid = false;
+        return;
+    }
+    if (depth >= kMaxSuggestDepth) {
+        n.types |= v.is_object() ? kObject : kArray;   // recorded, not described
+        return;
+    }
+    if (v.is_object()) {
+        n.types |= kObject;
+        ++n.objects;
+        for (const auto& [k, sub] : v.items()) {
+            auto& child = n.props[k];
+            if (!child) child = std::make_unique<SchemaSuggester::Inf>();
+            observe(*child, sub, depth + 1);
+        }
+        return;
+    }
+    // array
+    n.types |= kArray;
+    if (!n.items) n.items = std::make_unique<SchemaSuggester::Inf>();
+    for (const auto& el : v) observe(*n.items, el, depth + 1);
+}
+
+nlohmann::json describe(const SchemaSuggester::Inf& n, size_t depth, const std::string& path,
+                        const std::function<bool(const std::string&)>& noEnum) {
+    nlohmann::json out = nlohmann::json::object();
+    if (n.seen == 0) return out;   // e.g. items of arrays that were always empty
+    std::vector<std::string> types;
+    const std::pair<uint8_t, const char*> order[] = {{kObject, "object"}, {kArray, "array"},
+        {kString, "string"}, {kNumber, "number"}, {kBoolean, "boolean"}, {kNull, "null"}};
+    for (const auto& [bit, name] : order) {
+        if (!(n.types & bit)) continue;
+        types.push_back(bit == kNumber && n.allIntegral ? "integer" : name);
+    }
+    if (types.size() == 1) out["type"] = types.front();
+    else out["type"] = types;
+
+    std::vector<std::string> notes;
+    if ((n.types & kObject) && depth < kMaxSuggestDepth && n.objects > 0) {
+        nlohmann::json props = nlohmann::json::object();
+        nlohmann::json required = nlohmann::json::array();
+        for (const auto& [k, child] : n.props) {
+            props[k] = describe(*child, depth + 1, path.empty() ? k : path + "." + k, noEnum);
+            // Present in every object seen here. A key whose value was null is
+            // still present.
+            if (child->seen == n.objects) required.push_back(k);
+        }
+        out["properties"] = props;
+        if (!required.empty()) out["required"] = required;
+        out["additionalProperties"] = false;
+    }
+    if ((n.types & kArray) && n.items && depth < kMaxSuggestDepth) {
+        out["items"] = describe(*n.items, depth + 1, path + "[]", noEnum);
+    }
+    if (n.types & kString) {
+        if (n.allDateTime) out["format"] = "date-time";
+        else if (n.allDate) out["format"] = "date";
+        else if (n.allUuid) out["format"] = "uuid";
+        else if (n.allEmail) out["format"] = "email";
+        else if (!(noEnum && noEnum(path)) && !n.distinctOverflow && !n.distinct.empty() &&
+                 n.strings >= 3 * n.distinct.size() && !(n.types & ~(kString | kNull))) {
+            nlohmann::json e = nlohmann::json::array();
+            for (const auto& x : n.distinct) e.push_back(x);
+            if (n.types & kNull) e.push_back(nullptr);
+            out["enum"] = e;
+        }
+        notes.push_back("observed length " + std::to_string(n.minLen) + ".." + std::to_string(n.maxLen));
+    }
+    if ((n.types & kNumber) && n.minNum && n.maxNum) {
+        notes.push_back("observed range " + n.minNum->dump() + ".." + n.maxNum->dump());
+    }
+    if (!notes.empty()) {
+        std::string d;
+        for (const auto& x : notes) d += (d.empty() ? "" : "; ") + x;
+        out["description"] = d + " (not enforced)";
+    }
+    return out;
+}
+
+}  // namespace
+
+void SchemaSuggester::add(const nlohmann::json& document) {
+    ++rows_;
+    observe(*root_, document, 0);
+}
+
+nlohmann::json SchemaSuggester::result() const {
+    nlohmann::json s = describe(*root_, 0, "", noEnum_);
+    if (rows_ == 0) {
+        // Nothing to learn from: any object.
+        s = nlohmann::json{{"type", "object"}};
+    }
+    s["$schema"] = "https://json-schema.org/draft/2020-12/schema";
+    return s;
+}
+
+}  // namespace smartbotic::db::schema

+ 113 - 0
service/src/schema/json_schema.hpp

@@ -0,0 +1,113 @@
+// v2.16.0 - per-collection JSON Schema validation.
+//
+// A collection may carry a JSON Schema; every write's resulting document body
+// (user fields only: metadata and `_vector` are not part of it) must conform.
+// This is a SUBSET of JSON Schema (2020-12 keyword meanings), compiled once and
+// evaluated on every write:
+//
+//   type (string or array of: object array string integer number boolean null)
+//   properties, required, additionalProperties (bool or schema),
+//   minProperties, maxProperties
+//   minLength, maxLength (Unicode code points, as JSON Schema counts them),
+//   pattern (RE2 syntax, unanchored like JSON Schema), format (date-time, date,
+//   email, uuid)
+//   minimum, maximum, exclusiveMinimum, exclusiveMaximum (numbers)
+//   items (one schema for every element), minItems, maxItems, uniqueItems
+//   enum, const
+//   annotations, accepted and ignored: $schema $id $comment title description
+//   default examples readOnly writeOnly deprecated
+//
+// Any OTHER keyword is refused when the schema is compiled - $ref, allOf,
+// anyOf, oneOf, not, if/then/else, patternProperties, multipleOf, ... - so a
+// schema can never look stricter than what is enforced. `default` is an
+// annotation in JSON Schema and is NOT applied to documents.
+//
+// Patterns use RE2 (linear time, no recursion), not std::regex: a pattern runs
+// on every write against caller-supplied strings, and std::regex can take
+// exponential time or overflow the stack on long inputs.
+
+#pragma once
+
+#include <cstddef>
+#include <functional>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <nlohmann/json.hpp>
+
+namespace smartbotic::db::schema {
+
+struct Violation {
+    std::string path;      // "name", "address.zip", "tags[2]"; "" = the document itself
+    std::string keyword;   // the keyword that failed, e.g. "maxLength"
+    std::string message;   // human-readable, names the limit and the value's size
+};
+
+struct Node;   // compiled form, opaque
+
+class CompiledSchema {
+public:
+    explicit CompiledSchema(std::shared_ptr<const Node> root) : root_(std::move(root)) {}
+    // Up to `maxViolations` violations, in document order; empty = conforms.
+    // `total`, when given, receives the full count.
+    std::vector<Violation> validate(const nlohmann::json& document,
+                                    size_t maxViolations = 10,
+                                    size_t* total = nullptr) const;
+
+private:
+    std::shared_ptr<const Node> root_;
+};
+
+struct CompileResult {
+    std::shared_ptr<const CompiledSchema> schema;   // null on error
+    std::string error;                             // names the keyword and its path
+};
+
+// Compile a schema. Refuses: a non-object schema, a keyword outside the
+// supported subset, a keyword with a value of the wrong type, an invalid
+// pattern, and a root that could not accept an object (a document is always
+// an object).
+CompileResult compile(const nlohmann::json& schema);
+
+// "a; b; c (and N more)" for an error message.
+std::string summarize(const std::vector<Violation>& violations, size_t total);
+
+// v2.16.0 - suggest a schema from existing rows (SuggestCollectionSchema).
+//
+// Feed it document bodies with add(); result() returns a schema that EVERY
+// added row conforms to, by construction:
+//   - type: the union of the JSON types seen ("integer" when every number was
+//     integral); a field that held null gets "null" in its type;
+//   - required: the properties present in every object seen at that path;
+//   - additionalProperties: false - the properties seen are the whole list, which
+//     is what "a collection with fixed keys" means; edit before applying if
+//     more keys are expected;
+//   - 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 at least
+//     three times on average (a small closed set, not a sample of free text);
+//   - lengths and numeric ranges are reported in `description`, NOT enforced:
+//     the observed maximum is a fact about today's data, not a rule. Turn one
+//     into maxLength / maximum by hand where it is a rule.
+// Nesting deeper than 8 levels is left unconstrained ({}).
+class SchemaSuggester {
+public:
+    SchemaSuggester();
+    ~SchemaSuggester();
+    void add(const nlohmann::json& document);
+    nlohmann::json result() const;
+    // Paths ("a", "a.b", "tags[]") whose values must never be listed in an
+    // `enum` - sensitive fields, whose plaintext the suggestion would otherwise
+    // hand to the caller.
+    void setNoEnumPaths(std::function<bool(const std::string& path)> pred) { noEnum_ = std::move(pred); }
+    uint64_t rows() const { return rows_; }
+
+    struct Inf;   // per-path observations (defined in the .cpp)
+
+private:
+    std::unique_ptr<Inf> root_;
+    std::function<bool(const std::string&)> noEnum_;
+    uint64_t rows_ = 0;
+};
+
+}  // namespace smartbotic::db::schema

+ 57 - 0
service/src/schema/schema_registry.hpp

@@ -0,0 +1,57 @@
+// v2.16.0 - the compiled schemas currently armed, keyed by the collection's
+// canonical (project-qualified) name. Read on every write to a collection that
+// has a schema, so lookups take a shared lock and hand back a shared_ptr: a
+// schema replaced while a write is validating stays alive until that write is
+// done with it.
+
+#pragma once
+
+#include <atomic>
+#include <memory>
+#include <shared_mutex>
+#include <string>
+#include <unordered_map>
+
+#include <nlohmann/json.hpp>
+
+#include "schema/json_schema.hpp"
+
+namespace smartbotic::db::schema {
+
+struct SchemaEntry {
+    std::shared_ptr<const CompiledSchema> compiled;
+    nlohmann::json source;   // as declared, returned by GetCollectionSchema
+    bool audit = false;      // audit: log + count, let the write through
+    // Since this entry was armed (i.e. since boot or the last change).
+    std::atomic<uint64_t> auditViolations{0};
+    std::atomic<uint64_t> refusals{0};
+};
+
+class SchemaRegistry {
+public:
+    std::shared_ptr<SchemaEntry> get(const std::string& key) const {
+        if (count_.load(std::memory_order_relaxed) == 0) return nullptr;   // the common case
+        std::shared_lock lock(mu_);
+        auto it = map_.find(key);
+        return it == map_.end() ? nullptr : it->second;
+    }
+
+    // Returns the entry it replaced (null if none), so a refused change can be
+    // undone exactly.
+    std::shared_ptr<SchemaEntry> set(const std::string& key, std::shared_ptr<SchemaEntry> entry) {
+        std::unique_lock lock(mu_);
+        std::shared_ptr<SchemaEntry> previous;
+        if (auto it = map_.find(key); it != map_.end()) previous = it->second;
+        if (entry) map_[key] = std::move(entry);
+        else map_.erase(key);
+        count_.store(map_.size(), std::memory_order_relaxed);
+        return previous;
+    }
+
+private:
+    mutable std::shared_mutex mu_;
+    std::unordered_map<std::string, std::shared_ptr<SchemaEntry>> map_;
+    std::atomic<size_t> count_{0};
+};
+
+}  // namespace smartbotic::db::schema

+ 2 - 1
service/src/server_capabilities.hpp

@@ -18,7 +18,7 @@
 
 namespace smartbotic::database {
 
-inline constexpr std::array<std::string_view, 21> kServerCapabilities = {
+inline constexpr std::array<std::string_view, 22> kServerCapabilities = {
     "projects",              // 2.3.0  <project>:<collection> namespaces
     "access_policy",         // 2.7.0  row/column security
     "query_projection",      // 2.7.1  FindRequest.projection
@@ -40,6 +40,7 @@ inline constexpr std::array<std::string_view, 21> kServerCapabilities = {
     "filtered_similarity",   // 2.14.0 SimilaritySearchRequest.filters
     "server_info",           // 2.15.0 GetServerInfo itself
     "client_version_header", // 2.15.0 the server reads sbdb-client-version
+    "collection_schema",     // 2.16.0 Set/Get/SuggestCollectionSchema, schema_violation
 };
 
 }  // namespace smartbotic::database

+ 19 - 0
tests/CMakeLists.txt

@@ -892,3 +892,22 @@ target_link_libraries(test_relation_manager PRIVATE Threads::Threads)
 # migration_runner.cpp uses RAND_bytes for the generate_secret op.
 target_link_libraries(test_relation_manager PRIVATE OpenSSL::Crypto)
 add_test(NAME test_relation_manager COMMAND test_relation_manager)
+
+# v2.16.0 - collection schema validator + suggester.
+add_executable(test_json_schema
+    test_json_schema.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/schema/json_schema.cpp
+)
+find_path(TEST_RE2_INCLUDE_DIR re2/re2.h REQUIRED)
+find_library(TEST_RE2_LIBRARY re2 REQUIRED)
+target_include_directories(test_json_schema PRIVATE
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src
+    ${TEST_RE2_INCLUDE_DIR}
+)
+target_link_libraries(test_json_schema PRIVATE ${TEST_RE2_LIBRARY})
+if(TARGET nlohmann_json::nlohmann_json)
+    target_link_libraries(test_json_schema PRIVATE nlohmann_json::nlohmann_json)
+else()
+    target_include_directories(test_json_schema PRIVATE ${NLOHMANN_JSON_INCLUDE_DIRS})
+endif()
+add_test(NAME test_json_schema COMMAND test_json_schema)

+ 292 - 0
tests/load_test/test_collection_schema.cpp

@@ -0,0 +1,292 @@
+// v2.16.0 client/server boundary test: per-collection JSON Schema.
+//
+// What must hold, over real gRPC:
+//   - a collection WITHOUT a schema behaves exactly as before;
+//   - with one, EVERY write path refuses a non-conforming result (insert,
+//     upsert, update, updateIfVersion, patch on the merged body, increment,
+//     restore of an old version) with INVALID_ARGUMENT, reason
+//     schema_violation, and the violating fields named - and a refused write
+//     leaves the row untouched;
+//   - setting a schema over existing data validates it first: enforce refuses
+//     with examples, audit applies and counts;
+//   - the schema reads back exactly as set; remove works;
+//   - a suggested schema accepts every row it came from;
+//   - a sensitive (encrypted) field is judged by its plaintext;
+//   - it all survives a restart.
+// Phases (test_collection_schema.sh): write, check (after a restart).
+
+#include <smartbotic/database/client.hpp>
+
+#include <algorithm>
+#include <iostream>
+#include <string>
+#include <vector>
+
+using namespace smartbotic::database;
+using json = nlohmann::json;
+using Mode = Client::SchemaMode;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+static Client::Config cfg() {
+    Client::Config c;
+    c.address = "127.0.0.1:9028";
+    c.project = "sc";
+    c.writeRetries = 0;
+    return c;
+}
+
+static const json kPeople = {
+    {"type", "object"},
+    {"required", {"name"}},
+    {"additionalProperties", false},
+    {"properties", {
+        {"name", {{"type", "string"}, {"maxLength", 128}}},
+        {"age", {{"type", "integer"}, {"minimum", 0}}},
+        {"email", {{"type", "string"}, {"format", "email"}}},
+        {"tags", {{"type", "array"}, {"items", {{"type", "string"}}}}},
+        {"nick", {{"type", json::array({"string", "null"})}}}}}};
+
+static bool hasField(const Client::FailureDetail& d, const std::string& f) {
+    return std::find(d.fields.begin(), d.fields.end(), f) != d.fields.end();
+}
+
+// An insert must be refused with schema_violation naming `field`.
+static void insertRefused(Client& c, const std::string& coll, const json& doc, const std::string& field,
+                          const std::string& what) {
+    try {
+        c.insert(coll, doc);
+        ck(false, what + ": accepted");
+    } catch (const Client::Error& e) {
+        const auto* d = Client::errorDetail(e);
+        ck(e.code() == Client::ErrorCode::InvalidArgument && d && d->reason == "schema_violation" &&
+               hasField(*d, field),
+           what + ": InvalidArgument/schema_violation naming '" + field + "' (got " + e.what() + ")");
+    }
+}
+
+static int write() {
+    Client c(cfg());
+    c.connect();
+    ck(c.serverSupports(Client::Capability::kCollectionSchema), "server reports collection_schema");
+
+    // ---- a collection without a schema is unchanged ----
+    c.createCollection("free");
+    ck(!c.getCollectionSchema("free").has_value(), "no schema reads back as nullopt");
+    ck(!c.insert("free", {{"anything", json::array({1, "x", nullptr})}, {"name", std::string(500, 'z')}}).empty(),
+       "a collection without a schema accepts anything");
+
+    // ---- set at creation ----
+    c.createCollection("people");
+    auto r = c.setCollectionSchema("people", kPeople);
+    ck(r.success && r.rowsChecked == 0, "schema set on an empty collection");
+    auto got = c.getCollectionSchema("people");
+    ck(got && got->schema == kPeople && got->mode == Mode::Enforce && got->armed, "reads back exactly as set");
+
+    // ---- the owner's example ----
+    const auto id = c.insert("people", {{"name", std::string(128, 'a')}, {"age", 30}});
+    ck(!id.empty(), "name of 128 accepted");
+    insertRefused(c, "people", {{"name", std::string(130, 'a')}}, "name", "name of 130");
+    insertRefused(c, "people", {{"age", 3}}, "name", "missing required name");
+    insertRefused(c, "people", {{"name", "x"}, {"extra", 1}}, "extra", "unknown key with additionalProperties false");
+    insertRefused(c, "people", {{"name", "x"}, {"age", "3"}}, "age", "age as a string");
+    insertRefused(c, "people", {{"name", "x"}, {"age", -1}}, "age", "age below minimum");
+    insertRefused(c, "people", {{"name", "x"}, {"email", "nope"}}, "email", "bad email");
+    insertRefused(c, "people", {{"name", "x"}, {"tags", {"a", 2}}}, "tags[1]", "array element type");
+    ck(!c.insert("people", {{"name", "x"}, {"nick", nullptr}}).empty(), "null allowed where the type says so");
+    {
+        // The message names the size and the limit.
+        try {
+            c.insert("people", {{"name", std::string(130, 'a')}});
+        } catch (const Client::Error& e) {
+            const std::string m = e.what();
+            ck(m.find("130") != std::string::npos && m.find("128") != std::string::npos,
+               "message gives size and limit: " + m);
+        }
+    }
+
+    // ---- every other write path, and a refused write leaves the row alone ----
+    const auto before = c.get("people", id);
+    {
+        Client::FailureDetail fd;
+        ck(!c.update("people", id, {{"name", 5}}, fd) && fd.reason == "schema_violation" && hasField(fd, "name"),
+           "update refused (" + fd.reason + ")");
+    }
+    {
+        Client::FailureDetail fd;
+        const uint64_t v = before ? before->value("_version", 0ULL) : 0;
+        ck(!c.updateIfVersion("people", id, {{"age", 1}}, v, fd) && fd.reason == "schema_violation" &&
+               hasField(fd, "name"),
+           "updateIfVersion refused: the whole body must conform (" + fd.reason + ")");
+    }
+    {
+        Client::FailureDetail fd;
+        ck(c.patch("people", id, {{"age", "old"}}, fd) == 0 && fd.reason == "schema_violation" && hasField(fd, "age"),
+           "patch refused on a bad value (" + fd.reason + ")");
+    }
+    {
+        Client::FailureDetail fd;
+        // RFC 7396: null REMOVES the field - the merged body lacks a required key.
+        ck(c.patch("people", id, {{"name", nullptr}}, fd) == 0 && fd.reason == "schema_violation" &&
+               hasField(fd, "name"),
+           "patch removing a required field refused (" + fd.reason + ")");
+    }
+    {
+        Client::FailureDetail fd;
+        ck(!c.increment("people", id, {{"age", -1000}}, fd).has_value() && fd.reason == "schema_violation",
+           "increment below minimum refused (" + fd.reason + ")");
+    }
+    {
+        bool refused = false;
+        try {
+            c.upsert("people", {{"name", 1}}, id);
+        } catch (const Client::Error& e) {
+            const auto* d = Client::errorDetail(e);
+            refused = d && d->reason == "schema_violation";
+        }
+        ck(refused, "upsert refused");
+    }
+    ck(c.get("people", id) == before, "after six refused writes the row is unchanged");
+    ck(c.patch("people", id, {{"age", 31}}) > 0, "a conforming patch still works");
+
+    // ---- restore of an old version that breaks today's schema ----
+    // Control first: without a schema the same restore SUCCEEDS, so the
+    // refusal below is the schema's doing and not a restore that never works.
+    c.createCollection("hist0");
+    const auto h0 = c.insert("hist0", {{"a", "text"}});
+    ck(c.update("hist0", h0, {{"a", 1}}), "hist0 v2");
+    const auto rv = c.restoreVersion("hist0", h0, 1);
+    ck(rv > 0 && c.get("hist0", h0)->value("a", json()) == "text", "control: restore works without a schema");
+    c.createCollection("hist");
+    const auto hid = c.insert("hist", {{"a", "text"}});
+    ck(c.update("hist", hid, {{"a", 1}}), "hist v2");
+    ck(c.setCollectionSchema("hist", {{"properties", {{"a", {{"type", "integer"}}}}}}).success,
+       "schema over a conforming current row");
+    ck(c.restoreVersion("hist", hid, 1) == 0, "restoring a non-conforming old version is refused");
+    ck(c.get("hist", hid)->value("a", json()) == 1, "and the row keeps its conforming body");
+
+    // ---- existing data: enforce refuses with examples, audit applies and counts ----
+    c.createCollection("legacy");
+    for (int i = 0; i < 5; ++i) c.insert("legacy", {{"n", i}}, "ok" + std::to_string(i));
+    c.insert("legacy", {{"n", "five"}}, "bad1");
+    c.insert("legacy", {{"m", 1}}, "bad2");
+    const json legacy = {{"required", {"n"}}, {"properties", {{"n", {{"type", "integer"}}}}}};
+    auto e = c.setCollectionSchema("legacy", legacy);
+    ck(!e.success && e.rowsChecked == 7 && e.violatingRows == 2 && e.examples.size() == 2,
+       "enforce over 2 bad rows of 7 is refused with 2 examples (" + e.error + ")");
+    {
+        std::vector<std::string> ids;
+        for (const auto& x : e.examples) ids.push_back(x.id);
+        std::sort(ids.begin(), ids.end());
+        ck(ids == std::vector<std::string>{"bad1", "bad2"}, "the examples are the bad rows");
+    }
+    ck(!c.getCollectionSchema("legacy").has_value(), "a refused schema is not applied");
+    ck(!c.insert("legacy", {{"n", "still free"}}).empty(), "and writes are not validated");
+    auto a = c.setCollectionSchema("legacy", legacy, Mode::Audit);
+    ck(a.success && a.violatingRows == 3, "audit applies over bad rows and reports them");
+    ck(!c.insert("legacy", {{"n", "audited"}}).empty(), "audit lets a bad write through");
+    auto la = c.getCollectionSchema("legacy");
+    ck(la && la->mode == Mode::Audit && la->auditViolations == 1, "and counts it");
+
+    // ---- invalid schemas ----
+    {
+        auto bad = c.setCollectionSchema("free", {{"anyOf", json::array()}});
+        ck(!bad.success && bad.reason == "invalid_schema", "an unsupported keyword is refused (" + bad.reason + ")");
+        auto bad2 = c.setCollectionSchema("free", {{"type", "string"}});
+        ck(!bad2.success && bad2.reason == "invalid_schema", "a root that cannot be an object is refused");
+        ck(!c.getCollectionSchema("free").has_value(), "and nothing is applied");
+    }
+
+    // ---- remove ----
+    c.createCollection("tmp");
+    ck(c.setCollectionSchema("tmp", {{"additionalProperties", false}}).success, "tmp strict");
+    insertRefused(c, "tmp", {{"x", 1}}, "x", "tmp refuses before removal");
+    ck(c.removeCollectionSchema("tmp").success, "remove");
+    ck(!c.getCollectionSchema("tmp").has_value(), "removed schema reads back as nullopt");
+    ck(!c.insert("tmp", {{"x", 1}}).empty(), "writes are free again");
+
+    // ---- suggest, apply, it fits ----
+    c.createCollection("sug");
+    for (int i = 0; i < 40; ++i) {
+        json d = {{"title", "item " + std::to_string(i)}, {"qty", i}, {"price", i * 1.5},
+                  {"state", i % 3 == 0 ? "new" : "used"}, {"at", "2026-10-09T12:00:00Z"},
+                  {"meta", {{"src", "x"}}}};
+        if (i % 4 == 0) d["note"] = "n";
+        c.insert("sug", d);
+    }
+    auto s = c.suggestCollectionSchema("sug");
+    ck(s.rowsScanned == 40 && s.complete, "suggest scanned all 40");
+    auto applied = c.setCollectionSchema("sug", s.schema);
+    ck(applied.success && applied.rowsChecked == 40 && applied.violatingRows == 0,
+       "the suggestion applies in enforce mode over the rows it came from (" + applied.error + ")");
+    insertRefused(c, "sug", {{"title", "t"}, {"qty", 1}, {"price", 1.0}, {"state", "new"},
+                             {"at", "2026-10-09T12:00:00Z"}, {"meta", {{"src", "x"}}}, {"surprise", 1}},
+                  "surprise", "a key the data never had is refused");
+    insertRefused(c, "sug", {{"title", "t"}, {"qty", 1.5}, {"price", 1.0}, {"state", "new"},
+                             {"at", "2026-10-09T12:00:00Z"}, {"meta", {{"src", "x"}}}},
+                  "qty", "qty was always integral");
+    auto sample = c.suggestCollectionSchema("sug", 10);
+    ck(sample.rowsScanned == 10 && !sample.complete, "sample limit");
+
+    // ---- vectors and metadata are not part of the body ----
+    c.createCollection("vec", 0, false, 0, 4);
+    ck(c.setCollectionSchema("vec", {{"additionalProperties", false},
+                                     {"properties", {{"name", {{"type", "string"}}}}}}).success, "vec schema");
+    ck(!c.insert("vec", {{"name", "v"}, {"_vector", std::vector<float>{1, 0, 0, 0}}}).empty(),
+       "_vector is not an unknown key");
+
+    // ---- a sensitive field is judged by its plaintext ----
+    // The default sensitive patterns are `*.password` etc., which match a
+    // NESTED field only (a top-level `password` is not encrypted by default),
+    // so the field here is creds.password. test_collection_schema.sh greps the
+    // data directory for ciphertext, so this cannot pass vacuously.
+    c.createCollection("secrets");
+    ck(c.setCollectionSchema("secrets", {{"properties", {{"creds", {{"properties",
+                                         {{"password", {{"type", "string"}, {"maxLength", 10}}}}}}}}}}).success,
+       "secrets schema");
+    {
+        bool accepted = false;
+        try {
+            accepted = !c.insert("secrets", {{"creds", {{"password", "short"}}}}).empty();
+        } catch (const std::exception&) {
+        }
+        ck(accepted, "a 5-character password passes although its ciphertext is far longer");
+    }
+    insertRefused(c, "secrets", {{"creds", {{"password", "elevenchars"}}}}, "creds.password",
+                  "an 11-character password");
+    c.createCollection("secrets2");
+    for (int i = 0; i < 12; ++i) {
+        c.insert("secrets2", {{"creds", {{"password", i % 2 ? "hunter2" : "letmein"}}}, {"k", "a"}});
+    }
+    auto ss = c.suggestCollectionSchema("secrets2");
+    ck(!ss.schema["properties"]["creds"]["properties"]["password"].contains("enum") &&
+           ss.schema["properties"]["k"].contains("enum"),
+       "a sensitive field's values never appear in a suggested enum");
+    ck(ss.schema.dump().find("hunter2") == std::string::npos, "no plaintext anywhere in the suggestion");
+    return 0;
+}
+
+// After a restart: the schemas are back, armed, and enforced.
+static int check() {
+    Client c(cfg());
+    c.connect();
+    auto got = c.getCollectionSchema("people");
+    ck(got && got->schema == kPeople && got->armed && got->mode == Mode::Enforce, "people schema survives a restart");
+    insertRefused(c, "people", {{"name", std::string(130, 'a')}}, "name", "still enforced after restart");
+    auto la = c.getCollectionSchema("legacy");
+    ck(la && la->mode == Mode::Audit, "audit mode survives a restart");
+    ck(!c.getCollectionSchema("tmp").has_value(), "a removed schema stays removed");
+    ck(!c.insert("free", {{"z", 1}}).empty(), "a schema-less collection is still free");
+    return 0;
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "";
+    if (phase == "write") write();
+    else if (phase == "check") check();
+    else { std::cerr << "usage: write|check\n"; return 2; }
+    std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 80 - 0
tests/load_test/test_collection_schema.sh

@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# v2.16.0 client/server boundary e2e - per-collection JSON Schema. Encryption is
+# ON, so a sensitive field is checked by its plaintext. A restart between the
+# phases proves the schemas persist and are re-armed at boot. See
+# test_collection_schema.cpp.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-collection-schema
+PORT=9028
+
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": true, "key_file": "$DIR/data/storage.key" },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_collection_schema.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+stop() {
+    [[ -n "$SERVER_PID" ]] || return 0
+    kill -CONT "$SERVER_PID" 2>/dev/null || true
+    kill "$SERVER_PID" 2>/dev/null || true
+    wait "$SERVER_PID" 2>/dev/null || true
+    SERVER_PID=""
+}
+trap stop EXIT
+
+start_server() {
+    "$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" >> "$DIR/server.log" 2>&1 &
+    SERVER_PID=$!
+    for _ in $(seq 1 60); do
+        [[ $(grep -c "Notified systemd: READY" "$DIR/server.log") -ge $1 ]] && return 0
+        sleep 0.5
+    done
+    tail -30 "$DIR/server.log"; exit 1
+}
+
+run() {
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1" 2>&1 | grep -v '\[error\]' | tee "$DIR/out-$1.txt"
+    local rc=${PIPESTATUS[0]}
+    set -e
+    [[ $rc -eq 0 ]] || { echo "FAILED in phase $1"; tail -20 "$DIR/server.log"; exit $rc; }
+}
+
+: > "$DIR/server.log"
+start_server 1
+echo "=== write ==="
+run write
+echo "=== restart ==="
+stop
+# The sensitive-field checks above mean something only if values really are
+# stored encrypted.
+grep -rqaF '$ENC$' "$DIR/data" || { echo "FAIL: no ciphertext on disk - encryption checks were vacuous"; exit 1; }
+start_server 2
+grep -q "schema(s) armed" "$DIR/server.log" || { echo "FAIL: no schemas armed at boot"; exit 1; }
+echo "=== check ==="
+run check
+
+echo ""
+echo "OK - collection schema e2e passed"

+ 23 - 3
tests/load_test/test_server_info.cpp

@@ -42,7 +42,7 @@ static const std::vector<const char*> kAllCaps = {
     Cap::kUniqueIndexes, Cap::kErrorDetail, Cap::kPatchIfVersion, Cap::kIncrement,
     Cap::kCompositeUnique, Cap::kBatchDeleteIds, Cap::kEventActor, Cap::kVectorReadback,
     Cap::kExportCollection, Cap::kWriteSizeGuard, Cap::kFilteredSimilarity, Cap::kServerInfo,
-    Cap::kClientVersionHeader,
+    Cap::kClientVersionHeader, Cap::kCollectionSchema,
 };
 
 // Ordinary calls a client of any version makes; they must work across versions.
@@ -86,11 +86,19 @@ static int current(const std::string& version) {
 static int old() {
     Client c(cfg());
     ck(c.connect(), "old: connect");
+    // An "older server" is either pre-2.15.0 (no GetServerInfo: nullopt) or
+    // 2.15.0+ but older than this client (answers, and lacks this release's
+    // newest capability). Either way: no error, and the new feature is absent.
     bool threw = false;
     std::optional<Client::ServerInfo> si;
     try { si = c.serverInfo(); } catch (...) { threw = true; }
-    ck(!threw && !si.has_value(), "old: serverInfo is nullopt, not an error");
-    ck(!c.serverSupports(Cap::kServerInfo), "old: serverSupports is false");
+    ck(!threw, "old: serverInfo answers without an error");
+    if (!si) {
+        ck(!c.serverSupports(Cap::kServerInfo), "old (pre-2.15.0): serverSupports is false");
+    } else {
+        ck(si->version != clientLibraryVersion(), "old (2.15.0+): reports its own version " + si->version);
+        ck(!c.serverSupports(Cap::kCollectionSchema), "old (2.15.0+): lacks collection_schema");
+    }
     basics(c, "old");
     // A pre-2.14.0 server would answer a filtered search UNFILTERED; a 2.14.0
     // one applies it. Either way the answer must never be unfiltered rows.
@@ -105,6 +113,18 @@ static int old() {
         refused = d && d->reason == "filters_unsupported";
     }
     ck(refused || r.empty(), "old: a filtered search is refused or really filtered, never unfiltered");
+    // v2.16.0 - the first feature gated by capability: refused BEFORE sending.
+    const auto sr = c.setCollectionSchema("w", {{"type", "object"}});
+    ck(!sr.success && sr.reason == "server_unsupported",
+       "old: setCollectionSchema refused with server_unsupported (got '" + sr.reason + "')");
+    bool getRefused = false;
+    try {
+        (void)c.getCollectionSchema("w");
+    } catch (const Client::FailedPrecondition& e) {
+        const auto* d = Client::errorDetail(e);
+        getRefused = d && d->reason == "server_unsupported";
+    }
+    ck(getRefused, "old: getCollectionSchema refused with server_unsupported");
     return 0;
 }
 

+ 239 - 0
tests/test_json_schema.cpp

@@ -0,0 +1,239 @@
+// v2.16.0 - the collection-schema validator and suggester, in isolation.
+//
+// What must hold: every supported keyword refuses what it should and accepts
+// what it should; an unsupported keyword is refused at compile time (so a
+// schema can never look stricter than what is enforced); lengths count
+// characters, not bytes; and a suggested schema accepts every row it was
+// suggested from.
+
+#include "schema/json_schema.hpp"
+
+#include <iostream>
+#include <string>
+
+using nlohmann::json;
+namespace sc = smartbotic::db::schema;
+
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+static std::shared_ptr<const sc::CompiledSchema> compiled(const json& s) {
+    auto r = sc::compile(s);
+    if (!r.schema) std::cerr << "compile error: " << r.error << "\n";
+    return r.schema;
+}
+static bool ok(const sc::CompiledSchema& s, const json& d) { return s.validate(d).empty(); }
+static std::string firstKeyword(const sc::CompiledSchema& s, const json& d) {
+    auto v = s.validate(d);
+    return v.empty() ? "" : v.front().keyword;
+}
+static std::string firstPath(const sc::CompiledSchema& s, const json& d) {
+    auto v = s.validate(d);
+    return v.empty() ? "<none>" : v.front().path;
+}
+
+static void test_the_owner_example() {
+    // "optional key 'name', max length 128, varchar": 130 is refused.
+    auto s = compiled({{"type", "object"},
+                       {"properties", {{"name", {{"type", "string"}, {"maxLength", 128}}}}}});
+    ck(s != nullptr, "example compiles");
+    ck(ok(*s, {{"name", std::string(128, 'a')}}), "name of 128 accepted");
+    ck(firstKeyword(*s, {{"name", std::string(130, 'a')}}) == "maxLength", "name of 130 refused by maxLength");
+    ck(firstPath(*s, {{"name", std::string(130, 'a')}}) == "name", "the violation names the field");
+    ck(ok(*s, json::object()), "name is optional");
+    ck(ok(*s, {{"other", 1}}), "other keys allowed by default (additionalProperties defaults to true)");
+    auto msg = s->validate({{"name", std::string(130, 'a')}}).front().message;
+    ck(msg.find("130") != std::string::npos && msg.find("128") != std::string::npos,
+       "the message gives the size and the limit: " + msg);
+}
+
+static void test_lengths_are_characters() {
+    auto s = compiled({{"properties", {{"n", {{"type", "string"}, {"maxLength", 3}, {"minLength", 2}}}}}});
+    ck(ok(*s, {{"n", "\xC3\xA1\xC3\xA9\xC3\xAD"}}), "3 two-byte characters (6 bytes) fit maxLength 3");
+    ck(firstKeyword(*s, {{"n", "\xC3\xA1\xC3\xA9\xC3\xAD\xC3\xB3"}}) == "maxLength", "4 characters do not");
+    ck(firstKeyword(*s, {{"n", "\xF0\x9F\x98\x80"}}) == "minLength", "one 4-byte emoji is 1 character");
+}
+
+static void test_types() {
+    auto s = compiled({{"properties", {
+        {"i", {{"type", "integer"}}}, {"n", {{"type", "number"}}}, {"b", {{"type", "boolean"}}},
+        {"z", {{"type", "null"}}}, {"a", {{"type", "array"}}}, {"o", {{"type", "object"}}},
+        {"sn", {{"type", json::array({"string", "null"})}}}}}});
+    ck(ok(*s, {{"i", 5}}), "integer 5");
+    ck(ok(*s, {{"i", 5.0}}), "5.0 is an integer (JSON Schema)");
+    ck(firstKeyword(*s, {{"i", 5.5}}) == "type", "5.5 is not an integer");
+    ck(firstKeyword(*s, {{"i", "5"}}) == "type", "\"5\" is not an integer");
+    ck(ok(*s, {{"n", 5}}) && ok(*s, {{"n", 5.5}}), "number takes both");
+    ck(firstKeyword(*s, {{"b", 1}}) == "type", "1 is not a boolean");
+    ck(ok(*s, {{"z", nullptr}}), "null");
+    ck(ok(*s, {{"a", json::array()}}) && firstKeyword(*s, {{"a", json::object()}}) == "type", "array vs object");
+    ck(ok(*s, {{"o", json::object()}}), "object");
+    ck(ok(*s, {{"sn", "x"}}) && ok(*s, {{"sn", nullptr}}) && firstKeyword(*s, {{"sn", 1}}) == "type",
+       "type array: string or null");
+}
+
+static void test_required_and_additional() {
+    auto s = compiled({{"type", "object"}, {"required", {"id", "name"}},
+                       {"properties", {{"id", {{"type", "integer"}}}, {"name", {{"type", "string"}}}}},
+                       {"additionalProperties", false}});
+    ck(ok(*s, {{"id", 1}, {"name", "x"}}), "exact keys accepted");
+    ck(firstKeyword(*s, {{"id", 1}}) == "required", "missing required name");
+    ck(firstPath(*s, {{"id", 1}}) == "name", "required violation names the missing key");
+    ck(firstKeyword(*s, {{"id", 1}, {"name", "x"}, {"extra", 2}}) == "additionalProperties", "extra key refused");
+    ck(ok(*s, {{"id", 1}, {"name", nullptr}}) == false, "null is not a string");
+    auto t = compiled({{"additionalProperties", {{"type", "integer"}}}});
+    ck(ok(*t, {{"a", 1}, {"b", 2}}) && firstKeyword(*t, {{"a", "x"}}) == "type",
+       "additionalProperties as a schema applies to unlisted keys");
+    auto u = compiled({{"minProperties", 1}, {"maxProperties", 2}});
+    ck(firstKeyword(*u, json::object()) == "minProperties", "minProperties");
+    ck(firstKeyword(*u, {{"a", 1}, {"b", 1}, {"c", 1}}) == "maxProperties", "maxProperties");
+}
+
+static void test_nested_and_arrays() {
+    auto s = compiled({{"properties", {
+        {"addr", {{"type", "object"}, {"required", {"zip"}},
+                  {"properties", {{"zip", {{"type", "string"}, {"pattern", "^[0-9]{4}$"}}}}}}},
+        {"tags", {{"type", "array"}, {"items", {{"type", "string"}, {"maxLength", 5}}},
+                  {"minItems", 1}, {"maxItems", 3}, {"uniqueItems", true}}}}}});
+    ck(ok(*s, {{"addr", {{"zip", "1234"}}}, {"tags", {"a", "b"}}}), "nested ok");
+    ck(firstPath(*s, {{"addr", {{"zip", "12a4"}}}}) == "addr.zip", "nested path is dotted");
+    ck(firstKeyword(*s, {{"addr", {{"zip", "12a4"}}}}) == "pattern", "pattern");
+    ck(firstPath(*s, {{"addr", json::object()}}) == "addr.zip", "nested required");
+    ck(firstPath(*s, {{"tags", {"a", "toolong"}}}) == "tags[1]", "array element path");
+    ck(firstKeyword(*s, {{"tags", json::array()}}) == "minItems", "minItems");
+    ck(firstKeyword(*s, {{"tags", {"a", "b", "c", "d"}}}) == "maxItems", "maxItems");
+    ck(firstKeyword(*s, {{"tags", {"a", "a"}}}) == "uniqueItems", "uniqueItems");
+}
+
+static void test_numbers_enum_const_format() {
+    auto s = compiled({{"properties", {
+        {"age", {{"type", "integer"}, {"minimum", 0}, {"maximum", 150}}},
+        {"p", {{"exclusiveMinimum", 0}, {"exclusiveMaximum", 1}}},
+        {"status", {{"enum", {"active", "disabled"}}}},
+        {"v", {{"const", 2}}},
+        {"at", {{"type", "string"}, {"format", "date-time"}}},
+        {"d", {{"format", "date"}}},
+        {"u", {{"format", "uuid"}}},
+        {"e", {{"format", "email"}}}}}});
+    ck(ok(*s, {{"age", 0}}) && ok(*s, {{"age", 150}}), "inclusive bounds");
+    ck(firstKeyword(*s, {{"age", -1}}) == "minimum" && firstKeyword(*s, {{"age", 151}}) == "maximum", "bounds");
+    ck(firstKeyword(*s, {{"p", 0}}) == "exclusiveMinimum" && firstKeyword(*s, {{"p", 1}}) == "exclusiveMaximum" &&
+       ok(*s, {{"p", 0.5}}), "exclusive bounds");
+    ck(ok(*s, {{"status", "active"}}) && firstKeyword(*s, {{"status", "gone"}}) == "enum", "enum");
+    ck(ok(*s, {{"v", 2.0}}) && firstKeyword(*s, {{"v", 3}}) == "const", "const compares numbers by value");
+    ck(ok(*s, {{"at", "2026-10-09T14:27:00Z"}}) && ok(*s, {{"at", "2026-10-09T14:27:00.123+02:00"}}),
+       "date-time accepted");
+    ck(firstKeyword(*s, {{"at", "2026-13-09T14:27:00Z"}}) == "format", "month 13 refused");
+    ck(firstKeyword(*s, {{"at", "2026-10-09 14:27:00"}}) == "format", "no T/zone refused");
+    ck(ok(*s, {{"d", "2024-02-29"}}) && firstKeyword(*s, {{"d", "2025-02-29"}}) == "format", "leap years");
+    ck(ok(*s, {{"u", "123e4567-e89b-12d3-a456-426614174000"}}) && firstKeyword(*s, {{"u", "123"}}) == "format", "uuid");
+    ck(ok(*s, {{"e", "a@b.co"}}) && firstKeyword(*s, {{"e", "a@b"}}) == "format" &&
+       firstKeyword(*s, {{"e", "a b@c.d"}}) == "format", "email");
+    ck(ok(*s, {{"d", 5}}), "format applies to strings only");
+}
+
+static void test_refusals_at_compile() {
+    for (const char* kw : {"$ref", "allOf", "anyOf", "oneOf", "not", "if", "patternProperties",
+                           "multipleOf", "dependentRequired", "$defs", "prefixItems"}) {
+        auto r = sc::compile({{kw, json::object()}});
+        ck(!r.schema && r.error.find(kw) != std::string::npos, std::string("refused: ") + kw);
+    }
+    ck(!sc::compile({{"properties", {{"a", {{"maxLength", -1}}}}}}).schema, "negative maxLength");
+    ck(!sc::compile({{"properties", {{"a", {{"pattern", "(unclosed"}}}}}}).schema, "bad pattern");
+    ck(!sc::compile({{"properties", {{"a", {{"pattern", "(a)\\1"}}}}}}).schema, "backreference (not RE2)");
+    ck(!sc::compile({{"format", "ipv4"}}).schema, "unknown format");
+    ck(!sc::compile({{"type", "string"}}).schema, "root must accept an object");
+    ck(!sc::compile({{"type", "strng"}}).schema, "unknown type name");
+    ck(!sc::compile(json::array()).schema, "schema must be an object");
+    ck(!sc::compile({{"items", json::array({json::object()})}}).schema, "tuple items refused");
+    auto r = sc::compile({{"title", "t"}, {"description", "d"}, {"$schema", "x"}, {"default", 1},
+                          {"examples", json::array()}, {"$comment", "c"}});
+    ck(r.schema != nullptr, "annotations accepted");
+    auto f = compiled({{"properties", {{"x", false}, {"y", true}}}});
+    ck(firstKeyword(*f, {{"x", 1}}) == "false" && ok(*f, {{"y", "anything"}}), "boolean subschemas");
+}
+
+static void test_violation_cap_and_total() {
+    auto s = compiled({{"additionalProperties", false}});
+    json d = json::object();
+    for (int i = 0; i < 25; ++i) d["k" + std::to_string(i)] = i;
+    size_t total = 0;
+    auto v = s->validate(d, 10, &total);
+    ck(v.size() == 10 && total == 25, "capped at 10, total 25");
+    ck(sc::summarize(v, total).find("and 15 more") != std::string::npos, "summary says how many more");
+}
+
+static void test_suggest() {
+    sc::SchemaSuggester g;
+    std::vector<json> rows;
+    for (int i = 0; i < 30; ++i) {
+        json d = {{"name", "user" + std::to_string(i)},
+                  {"age", i},
+                  {"score", i * 0.5},
+                  {"status", i % 2 ? "active" : "disabled"},
+                  {"created", "2026-10-09T14:27:00Z"},
+                  {"uid", "123e4567-e89b-12d3-a456-42661417400" + std::to_string(i % 10)},
+                  {"tags", {"t" + std::to_string(i % 3)}},
+                  {"addr", {{"zip", "1234"}, {"city", "x"}}}};
+        if (i % 3 == 0) d["nick"] = nullptr;
+        if (i % 5 == 0) d["note"] = "optional";
+        rows.push_back(d);
+        g.add(d);
+    }
+    const json s = g.result();
+    ck(g.rows() == 30, "30 rows observed");
+    auto c = sc::compile(s);
+    ck(c.schema != nullptr, "the suggestion compiles: " + c.error);
+    if (!c.schema) return;
+    bool all = true;
+    for (const auto& r : rows) all = all && c.schema->validate(r).empty();
+    ck(all, "EVERY suggested-from row conforms to the suggestion");
+    ck(s["properties"]["age"]["type"] == "integer", "integral numbers -> integer");
+    ck(s["properties"]["score"]["type"] == "number", "fractional -> number");
+    ck(s["properties"]["status"].contains("enum") && s["properties"]["status"]["enum"].size() == 2,
+       "small closed set -> enum");
+    ck(!s["properties"]["name"].contains("enum"), "30 distinct names are not an enum");
+    ck(s["properties"]["created"]["format"] == "date-time", "date-time detected");
+    ck(s["properties"]["uid"]["format"] == "uuid", "uuid detected");
+    ck(s["properties"]["nick"]["type"] == "null", "a field only ever null");
+    const auto req = s["required"];
+    auto has = [&](const char* k) { return std::find(req.begin(), req.end(), k) != req.end(); };
+    ck(has("name") && has("age") && !has("note") && !has("nick"), "required = present in every row");
+    ck(s["additionalProperties"] == false, "additionalProperties false at the root");
+    ck(s["properties"]["addr"]["additionalProperties"] == false && s["properties"]["addr"]["required"].size() == 2,
+       "nested objects described too");
+    ck(s["properties"]["tags"]["items"]["type"] == "string", "array items described");
+    ck(!s["properties"]["name"].contains("maxLength") &&
+       s["properties"]["name"]["description"].get<std::string>().find("observed length") != std::string::npos,
+       "lengths are reported, not enforced");
+    ck(c.schema->validate({{"name", "x"}}).size() > 0, "a row missing required fields is refused");
+
+    sc::SchemaSuggester empty;
+    auto e = sc::compile(empty.result());
+    ck(e.schema && e.schema->validate({{"anything", 1}}).empty(), "no rows -> any object");
+
+    sc::SchemaSuggester mixed;
+    mixed.add({{"v", 1}});
+    mixed.add({{"v", "x"}});
+    mixed.add({{"v", 2.5}});
+    auto m = mixed.result();
+    auto mc = sc::compile(m);
+    ck(mc.schema && mc.schema->validate({{"v", 1}}).empty() && mc.schema->validate({{"v", "x"}}).empty() &&
+       mc.schema->validate({{"v", 2.5}}).empty(), "mixed types -> a type union that accepts each");
+}
+
+int main() {
+    test_the_owner_example();
+    test_lengths_are_characters();
+    test_types();
+    test_required_and_additional();
+    test_nested_and_arrays();
+    test_numbers_enum_const_format();
+    test_refusals_at_compile();
+    test_violation_cap_and_total();
+    test_suggest();
+    std::cout << "test_json_schema: " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

部分文件因为文件数量过多而无法显示