Переглянути джерело

feat(collections): the optional per-collection JSON Schema (database 2.16.0)

Four routes under .../collections/{name}/schema, plus the write-path slug
and has_schema on the collection GET. 1256/1256 green; three new
integration tests that skip cleanly on a database without the capability,
because a red test on a correct deployment teaches people to ignore the
suite.

The capability check IS the right gate here, which is the exact inverse of
the rule for filtered similarity search, so the handler says so where
someone would otherwise copy the wrong pattern: collection_schema arrived in
2.16.0 and capability names gate features from 2.15.0 on, whereas
filtered_similarity predates the capability API and a 2.14.0 server reports
no capabilities while fully supporting filters.

Decisions worth their reasoning:

mode defaults by whether the collection holds data - enforce when empty,
audit when populated - and mode_defaulted reports which rule applied.
Enforce on real data usually refuses, and the counts are what an operator
needs first, so defaulting to enforce there would make the common case look
like the feature is broken. violating_rows is returned on success too,
because audit succeeds while rows violate and that would otherwise be
invisible.

Three slugs rather than one: invalid_schema says fix your schema,
schema_violation says fix your data, server_unsupported says upgrade the
database. 501 for the last one - not 503, because retrying never upgrades a
database, and not 422, because the request is valid and there is nothing in
the body to correct. That adds ErrCode::NotImplemented.

schema_violation is mapped in db_errors, NOT in the schema handler, because
it fires on the DOCUMENT routes where callers meet it - the index-route
lesson in reverse: fixing the handler where the feature lives would leave
every write path answering generic validation.

And details.fields is ALWAYS an array on that slug, with no singular field,
unlike duplicate_values. Several violating paths is the ordinary case, so
details.fields.forEach(...) must work for one path too; the singularising
form would make the obvious client code silently do nothing in the most
common case, which a caller would only discover after testing with a
two-error document.

suggest never applies what it suggests and says so in the payload
(applied:false), because lengths and ranges are described rather than
enforced - arming it unseen would create something stricter-looking than
what it checks. GET answers 404 no_schema with its own slug; DELETE is
idempotent like the index drop; has_schema is OMITTED rather than false when
the database is too old, so absent means "cannot be determined".

Docs in llms.txt and openapi.json. Also corrects the cross-type comparison
note from "emergent" to "changes in database 2.18.0", which is now decided
upstream and server-side.
fszontagh 1 місяць тому
батько
коміт
5837858d98

+ 16 - 1
api/llms.txt

@@ -74,7 +74,7 @@ Arbitrary JSON CRUD under a `kind=json` collection.
   - **THE TRAP THAT FOLLOWS, and it is a real one: a version-like value is a NUMBER or a STRING depending on how many dots it happens to have.** A client written and tested against `2026.1.3` works, ships, and silently returns nothing the day the value becomes `2027.1`. Double-quote it and the problem does not exist.
   - `productVersion:eq:'2026.1'` matches nothing: JSON has no single-quoted strings, so the value is the literal six-plus characters `'2026.1'` INCLUDING the quote marks.
   - The operators are `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `contains`, `exists`, `regex`, `search`. **It is `ne`, not `neq`** - an unknown operator is refused 400 `bad_filter` naming it, which is deliberate: a mistyped operator must never be guessed at.
-  **COMPARISONS ORDER ACROSS TYPES, SO A RANGE CAN MATCH A VALUE OF A DIFFERENT KIND. This is EMERGENT behaviour, not a guarantee** - nobody specified it and the database may change it. Values order by TYPE: `null` < boolean < number < string. An ABSENT field is different again: every range operator, and `ne`, return FALSE for it. Measured on 2.17.2 over rows holding null, absent, `2024`, `2030`, `"1900"` (a string) and `true`:
+  **COMPARISONS ORDER ACROSS TYPES, SO A RANGE CAN MATCH A VALUE OF A DIFFERENT KIND - AND THIS CHANGES IN DATABASE 2.18.0.** It was never specified; it is being fixed. From 2.18.0 a range operator (`gt`/`gte`/`lt`/`lte`) matches only number-to-number or string-to-string, so a null, a boolean, an object, an array or a type mismatch never satisfies one on either side, and a null or boolean BOUND matches nothing (5 and 5.0 are both numbers, so they still compare). **`eq`/`ne` are NOT changing** - they keep JSON equality, so `eq null` still matches an explicit null and `ne 2024` still matches null, true and strings while still excluding an absent field. `exists` is unchanged. It is a SERVER-side change, so it takes effect when the database is upgraded and the client version is irrelevant; pin `smartbotic-database (>= 2.18.0)` when you want it. Until then, the behaviour below is what you get. Values order by TYPE: `null` < boolean < number < string. An ABSENT field is different again: every range operator, and `ne`, return FALSE for it. Measured on 2.17.2 over rows holding null, absent, `2024`, `2030`, `"1900"` (a string) and `true`:
   ```
   year:lte:2025  ->  null, true, 2024          <- null and a BOOLEAN pass a numeric upper bound
   year:lte:1900  ->  null, true
@@ -129,6 +129,21 @@ Example: `?filter=age:gte:30&filter=name:eq:Alice`.
 
 Additional query params: `limit` (default 20), `offset` (default 0), `sort` (field name), `desc` (bool).
 
+## Collection schema (needs database 2.16.0+)
+
+An OPTIONAL per-collection JSON Schema, validated on every write. All four routes answer **501** `server_unsupported` against an older database - not 503, because no amount of retrying upgrades a database, and not 422, because the request is valid and there is nothing in the body to fix. Read `has_schema` on the collection GET to know whether one is set; it is OMITTED there when the database is too old, so absent means "cannot be determined", never "no schema".
+
+- `GET    /api/v1/projects/{project}/collections/{name}/schema` - The schema as stored: `{schema, mode, audit_violations, refusals, armed}`. Needs only the **read** grant, deliberately: a schema is the contract you must satisfy to write, so anyone who may read the collection may see what shape it expects. **404 `no_schema`** when none is set - its own slug, so you can tell it from `not_found` (no such collection) without parsing a sentence. **`armed: false` means the stored schema no longer compiles and NOTHING is being validated** - check it, because a schema that silently enforces nothing reads as protection.
+- `PUT    /api/v1/projects/{project}/collections/{name}/schema` `{schema, mode?}` - Set or replace it (project-manage). Every EXISTING row is validated first. `mode` is `enforce` or `audit`; **an unknown key, or a misspelled mode, is 422 rather than silently defaulted.** Answers `{mode, mode_defaulted, rows_checked, violating_rows, examples}` - and note `violating_rows` is reported on SUCCESS too, because audit mode succeeds while rows violate, which is the entire point of audit and would be invisible if only failures carried counts.
+  **`mode` DEFAULTS BY WHETHER THE COLLECTION HOLDS DATA**, and the asymmetry is deliberate: `enforce` on an EMPTY collection (it cannot fail, and a live contract is what you want) and `audit` on a POPULATED one (enforce usually refuses on real data, and the counts are what you need first - defaulting to enforce there would make the common case look broken). `mode_defaulted` tells you which rule applied, so you never have to infer it.
+  In `enforce` mode one non-conforming row refuses the whole change: **422 `schema_violation`** with `details.rows_checked`, `details.violating_rows` and up to ten `details.examples` of `{id, message, fields}`. A schema outside the supported subset is **422 `invalid_schema`** instead - a different slug on purpose, because one says fix your schema and the other says fix your data.
+- `DELETE /api/v1/projects/{project}/collections/{name}/schema` - Remove it; writes stop being validated. **Idempotent** - removing a schema that is not there reaches the requested end state, so it is 200, not 404.
+- `GET    /api/v1/projects/{project}/collections/{name}/schema/suggest?sample_limit=N` - A schema generated FROM the data as a starting point (project-manage; it scans). Answers `{schema, rows_scanned, complete, applied}`. **`applied` is always `false`: this NEVER applies what it suggests.** Lengths and ranges are only described rather than enforced, so arming it unseen would create something that looks stricter than what it checks - edit it, then PUT it. `complete: false` means it was built from a sample, so a field absent from the suggestion may still exist in the data; it is emitted unconditionally, so absence means only "older server".
+
+**A WRITE refused by the schema is 422 `schema_violation` on the DOCUMENT routes** - insert, update, upsert, patch (judged on the MERGED result, so a small body can trip it), increment, batch and restoreVersion. **`error.details.fields` is ALWAYS AN ARRAY, even for a single path, and `field` is never present on this slug** - unlike `duplicate_values`, which singularises. That is deliberate: several violating paths is the ordinary case here, so `details.fields.forEach(...)` has to work for one path too. The paths are dotted and indexed (`addr.zip`, `tags[2]`). The values are deliberately NOT echoed back, so nothing sensitive is reflected; the message names the rule and the size.
+
+**The schema does not cover `_vector`.** A vector collection's dimension stays its `vector_dimension`, and the vector is not part of the validated body.
+
 ## Indexes and facets
 
 Project-scoped, under a collection. Index create/drop require a full (non-scoped) key with project access - scoped keys cannot manage indexes.

+ 346 - 0
api/openapi.json

@@ -4779,6 +4779,352 @@
           }
         }
       }
+    },
+    "/api/v1/projects/{project}/collections/{name}/schema": {
+      "get": {
+        "summary": "Get the collection's JSON Schema",
+        "tags": [
+          "documents"
+        ],
+        "description": "The schema as stored, with its mode and counters. Needs only the read grant: a schema is the contract a writer must satisfy, so anyone who may read the collection may see what shape it expects. 404 no_schema when none is set - its own slug, distinguishable from not_found without parsing the message. armed:false means the stored schema no longer compiles and NOTHING is being validated, which is worse than no schema because it reads as protection. Needs database 2.16.0+.",
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "name",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "The schema, its mode and counters",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "schema": {
+                      "type": "object"
+                    },
+                    "mode": {
+                      "type": "string",
+                      "enum": [
+                        "enforce",
+                        "audit"
+                      ]
+                    },
+                    "audit_violations": {
+                      "type": "integer"
+                    },
+                    "refusals": {
+                      "type": "integer"
+                    },
+                    "armed": {
+                      "type": "boolean"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "404": {
+            "description": "no_schema (none set) or not_found (no such collection)",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          },
+          "501": {
+            "description": "501 server_unsupported - the database predates 2.16.0. Not 503, because retrying never upgrades a database, and not 422, because the request is valid.",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          }
+        }
+      },
+      "put": {
+        "summary": "Set or replace the collection's JSON Schema",
+        "tags": [
+          "documents"
+        ],
+        "description": "Project-manage. Every existing row is validated first. mode is enforce or audit; an unknown key, or a misspelled mode, is 422 rather than silently defaulted. mode DEFAULTS by whether the collection holds data - enforce when empty (it cannot fail, and a live contract is wanted) and audit when populated (enforce usually refuses on real data, and the counts are what an operator needs first); mode_defaulted reports which rule applied. violating_rows is returned on SUCCESS too, because audit mode succeeds while rows violate - the whole point of audit, invisible if only failures carried counts. In enforce mode one non-conforming row refuses the change with 422 schema_violation carrying rows_checked, violating_rows and up to ten examples. A schema outside the supported subset is 422 invalid_schema instead: one says fix your schema, the other says fix your data. The schema does not cover _vector; dimension stays the collection's vector_dimension.",
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "name",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "requestBody": {
+          "required": true,
+          "content": {
+            "application/json": {
+              "schema": {
+                "type": "object",
+                "required": [
+                  "schema"
+                ],
+                "additionalProperties": false,
+                "properties": {
+                  "schema": {
+                    "type": "object",
+                    "description": "A JSON Schema subset with draft 2020-12 meanings"
+                  },
+                  "mode": {
+                    "type": "string",
+                    "enum": [
+                      "enforce",
+                      "audit"
+                    ]
+                  }
+                }
+              }
+            }
+          }
+        },
+        "responses": {
+          "200": {
+            "description": "Applied",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "mode": {
+                      "type": "string"
+                    },
+                    "mode_defaulted": {
+                      "type": "boolean"
+                    },
+                    "rows_checked": {
+                      "type": "integer"
+                    },
+                    "violating_rows": {
+                      "type": "integer"
+                    },
+                    "examples": {
+                      "type": "array",
+                      "items": {
+                        "type": "object",
+                        "properties": {
+                          "id": {
+                            "type": "string"
+                          },
+                          "message": {
+                            "type": "string"
+                          },
+                          "fields": {
+                            "type": "array",
+                            "items": {
+                              "type": "string"
+                            }
+                          }
+                        }
+                      }
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "422": {
+            "description": "schema_violation (existing rows), invalid_schema (unsupported schema), unknown_option, or validation",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          },
+          "501": {
+            "description": "501 server_unsupported - the database predates 2.16.0. Not 503, because retrying never upgrades a database, and not 422, because the request is valid.",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          }
+        }
+      },
+      "delete": {
+        "summary": "Remove the collection's JSON Schema",
+        "tags": [
+          "documents"
+        ],
+        "description": "Project-manage. Writes stop being validated. Idempotent: removing a schema that is not there reaches the requested end state, so it is 200 rather than 404.",
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "name",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "Removed",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "removed": {
+                      "type": "boolean"
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "404": {
+            "description": "Error",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          },
+          "501": {
+            "description": "501 server_unsupported - the database predates 2.16.0. Not 503, because retrying never upgrades a database, and not 422, because the request is valid.",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          }
+        }
+      }
+    },
+    "/api/v1/projects/{project}/collections/{name}/schema/suggest": {
+      "get": {
+        "summary": "Suggest a schema from the collection's data",
+        "tags": [
+          "documents"
+        ],
+        "description": "Project-manage, because it scans the collection and exists to author a contract rather than satisfy one. It NEVER applies what it suggests - applied is always false. Lengths and ranges are only described rather than enforced, so arming it unseen would create something that looks stricter than what it checks: edit it, then PUT it. complete:false means it was built from a sample, so a field absent from the suggestion may still exist in the data; it is emitted unconditionally, so absence means only an older server.",
+        "parameters": [
+          {
+            "name": "project",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "name",
+            "in": "path",
+            "required": true,
+            "schema": {
+              "type": "string"
+            }
+          },
+          {
+            "name": "sample_limit",
+            "in": "query",
+            "required": false,
+            "schema": {
+              "type": "integer",
+              "minimum": 0
+            },
+            "description": "0 or omitted scans every row"
+          }
+        ],
+        "responses": {
+          "200": {
+            "description": "A suggested schema",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "type": "object",
+                  "properties": {
+                    "schema": {
+                      "type": "object"
+                    },
+                    "rows_scanned": {
+                      "type": "integer"
+                    },
+                    "complete": {
+                      "type": "boolean"
+                    },
+                    "applied": {
+                      "type": "boolean",
+                      "enum": [
+                        false
+                      ]
+                    }
+                  }
+                }
+              }
+            }
+          },
+          "404": {
+            "description": "Error",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          },
+          "501": {
+            "description": "501 server_unsupported - the database predates 2.16.0. Not 503, because retrying never upgrades a database, and not 422, because the request is valid.",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
+          }
+        }
+      }
     }
   }
 }

+ 1 - 0
src/CMakeLists.txt

@@ -38,6 +38,7 @@ add_library(vectorapi_core STATIC
     handlers/keys.cpp
     handlers/collections.cpp
     handlers/indexes.cpp
+    handlers/collection_schema.cpp
     handlers/documents.cpp
     handlers/vectors.cpp
     handlers/stats.cpp

+ 44 - 0
src/db_errors.cpp

@@ -89,6 +89,50 @@ ApiError translate(Code code, const std::string& message, const std::string& not
                 // and silently matched nothing. So this refusal turns a silently
                 // empty result into a visible error.
                 return ApiError(ErrCode::Unprocessable, "encrypted_field", message, details);
+            if (reason == "schema_violation")
+                // A write refused by the collection's schema (database 2.16.0).
+                // Its own slug because the remedy is specific and the payload
+                // is the whole value of the answer: `details.fields` carries
+                // the violating PATHS (`addr.zip`, `tags[2]`), which is what a
+                // caller needs to fix the document. A generic `validation`
+                // would hand them a sentence and make them guess which field.
+                //
+                // Mapped HERE rather than in the schema handler, deliberately:
+                // this fires on the DOCUMENT routes - insert, update, upsert,
+                // patch on the merged result, increment, batch, restoreVersion -
+                // which is where callers meet it, and the schema handler never
+                // sees these at all. The index-route lesson is the same one in
+                // reverse: fixing the handler where the feature lives would
+                // leave every write path answering `validation`.
+                //
+                // The database deliberately does NOT echo the offending VALUES,
+                // only the paths and the rule, so nothing sensitive is reflected
+                // back - which is also why the message is passed through rather
+                // than rebuilt.
+            {
+                // `fields` is ALWAYS an array here, even for one path, which
+                // differs deliberately from every other slug in this function.
+                // `detailsJson` singularises a lone field to `field` because a
+                // unique-value collision almost always concerns exactly one and
+                // reads better that way. A schema violation does NOT: several
+                // paths is the ordinary case, so the natural client code is
+                // `details.fields.forEach(...)` - and under the singularising
+                // rule that silently does nothing for a single-path violation,
+                // which is the most common kind. A caller would test with a
+                // two-error document, ship, and see nothing for one-error ones.
+                // Same latent-break shape as a value that is a string only
+                // because it has enough dots in it.
+                //
+                // Safe to define this way because the slug is new and nothing
+                // consumes it yet; one shape chosen now beats two spellings
+                // forever, which is the reasoning that refused `Top_K`.
+                nlohmann::json sv = details;
+                if (sv.contains("field")) {
+                    sv["fields"] = nlohmann::json::array({sv["field"]});
+                    sv.erase("field");
+                }
+                return ApiError(ErrCode::Unprocessable, "schema_violation", message, sv);
+            }
             return ApiError(ErrCode::Unprocessable, "validation", message);
         case Code::OutOfRange:
             return ApiError(ErrCode::Unprocessable, "validation", message);

+ 8 - 0
src/errors.cpp

@@ -16,6 +16,14 @@ int httpStatus(ErrCode code) {
         // nothing was slow about the client, the upstream we were waiting on
         // did not answer. Nothing but function dispatch produces this.
         case ErrCode::GatewayTimeout:   return 504;
+        // The DATABASE is too old to perform what was asked - not a fault of
+        // ours and not a fault of the caller's. 501 rather than 503, because
+        // 503 means "retry as-is" and no amount of retrying upgrades a
+        // database; rather than 422, because the request is perfectly valid
+        // and there is nothing in the body to correct. The remedy is an
+        // operator action, so the status has to say "this server cannot do
+        // this" instead of blaming either side.
+        case ErrCode::NotImplemented:   return 501;
         case ErrCode::Internal:      return 500;
     }
     return 500;

+ 1 - 1
src/errors.hpp

@@ -7,7 +7,7 @@ namespace svapi {
 
 enum class ErrCode { BadRequest, Unauthorized, Forbidden, NotFound, Conflict,
                      Unprocessable, TooManyRequests, Unavailable, GatewayTimeout,
-                     Internal };
+                     NotImplemented, Internal };
 
 int httpStatus(ErrCode code);
 

+ 258 - 0
src/handlers/collection_schema.cpp

@@ -0,0 +1,258 @@
+#include "db_errors.hpp"
+#include "errors.hpp"
+#include "functions/known_keys.hpp"
+#include "json_http.hpp"
+#include "server.hpp"
+
+namespace svapi {
+namespace {
+
+using Db = smartbotic::database::Client;
+
+/// The capability check IS the right gate here, and that is the exact inverse
+/// of the rule for filtered similarity search - so the two must not be
+/// confused. `collection_schema` was introduced in database 2.16.0 and
+/// capability names gate features from 2.15.0 onward, so
+/// `serverSupports(kCollectionSchema)` answers correctly for it.
+/// `filtered_similarity` PREDATES the capability API: a 2.14.0 server reports
+/// no capabilities at all while fully supporting filters, so gating that on a
+/// name would silently drop onto the capped emulation against the very server
+/// we deployed for it. The rule: a capability name is sound for a feature
+/// introduced in 2.15.0 or later, and unsound for anything older.
+///
+/// Checked up front on every route rather than relying on the client's own
+/// refusal, for two reasons: we answer 501 with an operator-facing message
+/// instead of a translated FailedPrecondition, and a UI can ask once rather
+/// than discovering it per request.
+void requireSchemaSupport(ServerDeps& d) {
+    if (!d.db.client().serverSupports(Db::Capability::kCollectionSchema))
+        throw ApiError(ErrCode::NotImplemented, "server_unsupported",
+                       "this database does not support collection schemas; they need "
+                       "smartbotic-database 2.16.0 or later. Upgrading is an operator action - "
+                       "nothing in the request needs changing.");
+}
+
+const char* modeName(Db::SchemaMode m) {
+    return m == Db::SchemaMode::Audit ? "audit" : "enforce";
+}
+
+/// The violating rows a refused or audited change reported, as the caller
+/// needs them: the PATHS that failed rather than the values, which the
+/// database deliberately does not echo.
+nlohmann::json examplesJson(const std::vector<Db::SchemaRowViolation>& examples) {
+    nlohmann::json out = nlohmann::json::array();
+    for (const auto& v : examples) {
+        nlohmann::json fields = nlohmann::json::array();
+        for (const auto& f : v.fields) fields.push_back(f);
+        out.push_back({{"id", v.id}, {"message", v.message}, {"fields", fields}});
+    }
+    return out;
+}
+
+/// Turn a refused schema change into the right slug.
+///
+/// THREE outcomes that would all be `validation` if folded together, and the
+/// remedies have nothing in common: fix your schema, fix your data, or upgrade
+/// the database. Folding them would send a caller hunting a typo in a schema
+/// that is correct.
+ApiError schemaChangeError(const Db::SchemaChangeResult& r) {
+    if (r.reason == "server_unsupported")
+        return ApiError(ErrCode::NotImplemented, "server_unsupported",
+                        r.error.empty() ? "this database does not support collection schemas"
+                                        : r.error);
+    if (r.reason == "invalid_schema")
+        return ApiError(ErrCode::Unprocessable, "invalid_schema",
+                        r.error.empty() ? "the schema is outside the supported subset" : r.error);
+    // Existing rows do not satisfy it. The counts and the examples are the
+    // whole value of this answer: a caller told only "refused" cannot act.
+    if (r.violatingRows > 0)
+        return ApiError(ErrCode::Unprocessable, "schema_violation",
+                        r.error.empty()
+                            ? "existing rows do not satisfy this schema, so it was not applied"
+                            : r.error,
+                        {{"rows_checked", r.rowsChecked},
+                         {"violating_rows", r.violatingRows},
+                         {"examples", examplesJson(r.examples)}});
+    // No reason and no violations: a genuine failure rather than a verdict.
+    // 503 rather than a guessed 422 - the same rule as a reason-less
+    // FailedPrecondition, where answering 422 told a caller a read-only
+    // database was its own validation mistake.
+    return ApiError(ErrCode::Unavailable, "db_error",
+                    r.error.empty() ? "the database did not apply the schema" : r.error);
+}
+
+} // namespace
+
+void registerCollectionSchemaRoutes(ApiServer& s) {
+    auto& svr = s.raw();
+    ServerDeps* d = &s.deps();
+
+    // The schema as stored, with its mode and counters.
+    //
+    // A READ grant suffices, deliberately: a schema is the contract a caller
+    // must satisfy to write, so anyone who may read the collection may read
+    // what shape it expects. Withholding it would make a 422 unexplainable to
+    // the one principal most likely to hit it.
+    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        std::string project = req.matches[1], name = req.matches[2];
+        requireCapability(*d, k, req, project, name, KeyOp::Read);
+        requireSchemaSupport(*d);
+        if (!d->registry.get(project, name))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
+
+        const auto got = d->db.client().getCollectionSchema(qualify(project, name));
+        // 404 rather than 200 with a null: "this collection has no schema" is a
+        // DEFINITE answer about a sub-resource that does not exist, not an
+        // undetermined one, so there is no three-state problem to represent.
+        // A caller listing collections should read `has_schema` on the
+        // collection GET rather than probing this route per collection.
+        if (!got)
+            throw ApiError(ErrCode::NotFound, "no_schema",
+                           "this collection has no schema; writes are not validated");
+
+        sendJson(res, 200,
+                 {{"schema", got->schema},
+                  {"mode", modeName(got->mode)},
+                  // Counters since the schema was armed. `audit_violations`
+                  // is the one that matters in audit mode: it is how an
+                  // operator learns the data would fail enforcement.
+                  {"audit_violations", got->auditViolations},
+                  {"refusals", got->refusals},
+                  // `armed: false` means the stored schema no longer compiles
+                  // and NOTHING is being validated. Surfaced rather than
+                  // hidden, because a schema that silently enforces nothing is
+                  // worse than no schema - it reads as protection.
+                  {"armed", got->armed}});
+    });
+
+    // Set or replace the schema.
+    //
+    // Project-manage rather than admin: a schema is a data contract on the
+    // tenant's own collection, the same category as an index, and not a
+    // security boundary. (Function POLICY is admin-only because it governs
+    // what one project may take from a runner every project shares.)
+    svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        std::string project = req.matches[1], name = req.matches[2];
+        requireProjectManage(k, project);
+        requireSchemaSupport(*d);
+        if (!d->registry.get(project, name))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
+
+        nlohmann::json body = bodyJson(req);
+
+        // An unknown key is REFUSED, not ignored. The lesson from the vector
+        // search body applies verbatim: an option accepted and silently
+        // dropped is worse than one refused, and `mode: "enfroce"` must not
+        // quietly apply the default.
+        static constexpr std::initializer_list<std::string_view> kSchemaKeys = {"schema", "mode"};
+        if (const auto unknown = functions::unknownKeys(body, kSchemaKeys); !unknown.empty())
+            throw ApiError(ErrCode::Unprocessable, "unknown_option",
+                           functions::unknownKeyMessage(unknown, kSchemaKeys));
+
+        if (!body.contains("schema") || !body.at("schema").is_object())
+            throw ApiError(ErrCode::Unprocessable, "validation",
+                           "'schema' is required and must be a JSON Schema object");
+
+        const std::string qc = qualify(project, name);
+
+        // The DEFAULT MODE depends on whether the collection holds data, and
+        // the asymmetry is deliberate. On an EMPTY collection enforce can
+        // never fail, and a live contract is what the caller wants. On a
+        // POPULATED one enforce usually REFUSES on real data, and the counts
+        // are what an operator actually needs first - so defaulting to enforce
+        // there would make the common case look like the feature is broken.
+        // Stated in the response as `mode_defaulted` so a caller never has to
+        // infer which rule applied.
+        bool defaulted = false;
+        Db::SchemaMode mode = Db::SchemaMode::Enforce;
+        if (body.contains("mode")) {
+            if (!body.at("mode").is_string())
+                throw ApiError(ErrCode::Unprocessable, "validation", "'mode' must be a string");
+            const std::string m = body.at("mode").get<std::string>();
+            if (m == "audit") mode = Db::SchemaMode::Audit;
+            else if (m == "enforce") mode = Db::SchemaMode::Enforce;
+            else
+                throw ApiError(ErrCode::Unprocessable, "validation",
+                               "'mode' must be \"enforce\" or \"audit\", not \"" + m + "\"");
+        } else {
+            defaulted = true;
+            mode = d->db.client().count(qc) > 0 ? Db::SchemaMode::Audit : Db::SchemaMode::Enforce;
+        }
+
+        const auto r = d->db.client().setCollectionSchema(qc, body.at("schema"), mode);
+        if (!r.success) throw schemaChangeError(r);
+
+        // Reported on SUCCESS too, because audit mode succeeds while rows
+        // violate: `violating_rows` above zero here means the schema is armed
+        // and the data does not satisfy it, which is the whole point of audit
+        // and is invisible if only failures carry counts.
+        sendJson(res, 200,
+                 {{"mode", modeName(mode)},
+                  {"mode_defaulted", defaulted},
+                  {"rows_checked", r.rowsChecked},
+                  {"violating_rows", r.violatingRows},
+                  {"examples", examplesJson(r.examples)}});
+    });
+
+    // Remove the schema; writes stop being validated.
+    svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema)",
+               [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        std::string project = req.matches[1], name = req.matches[2];
+        requireProjectManage(k, project);
+        requireSchemaSupport(*d);
+        if (!d->registry.get(project, name))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
+
+        const auto r = d->db.client().removeCollectionSchema(qualify(project, name));
+        if (!r.success) throw schemaChangeError(r);
+        // Idempotent, like the index drop: removing a schema that is not there
+        // reaches the requested end state, so it is 200 rather than 404.
+        sendJson(res, 200, {{"removed", true}});
+    });
+
+    // A schema generated FROM the data, as a starting point.
+    //
+    // Project-manage rather than read: it scans the collection, and it exists
+    // to author a contract rather than to satisfy one.
+    //
+    // It NEVER applies what it suggests. The database's own note is the
+    // reason: lengths and ranges are only described, not enforced, so applying
+    // this unseen would arm something that looks stricter than what it
+    // actually checks. The caller edits and then PUTs.
+    svr.Get(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/schema/suggest)",
+            [d](const httplib::Request& req, httplib::Response& res) {
+        ApiKey k = requireKey(*d, req);
+        std::string project = req.matches[1], name = req.matches[2];
+        requireProjectManage(k, project);
+        requireSchemaSupport(*d);
+        if (!d->registry.get(project, name))
+            throw ApiError(ErrCode::NotFound, "not_found", "no such collection");
+
+        uint64_t sampleLimit = 0;  // 0 = every row
+        if (req.has_param("sample_limit")) {
+            const unsigned long long wide =
+                std::strtoull(req.get_param_value("sample_limit").c_str(), nullptr, 10);
+            sampleLimit = static_cast<uint64_t>(wide);
+        }
+
+        const auto sug = d->db.client().suggestCollectionSchema(qualify(project, name), sampleLimit);
+        sendJson(res, 200,
+                 {{"schema", sug.schema},
+                  {"rows_scanned", sug.rowsScanned},
+                  // `complete: false` means this was built from a SAMPLE, so a
+                  // field absent from it may still exist in the data and the
+                  // suggestion may be stricter than the collection. Emitted
+                  // unconditionally, so absence means only "older server".
+                  {"complete", sug.complete},
+                  // Said in the payload rather than only in the docs: the one
+                  // misreading that costs data is treating this as applied.
+                  {"applied", false}});
+    });
+}
+
+} // namespace svapi

+ 10 - 0
src/handlers/collections.cpp

@@ -153,6 +153,16 @@ void registerCollectionRoutes(ApiServer& s) {
         // needs: omitted means "could not be determined", never "disabled".
         if (auto enforced = d->db.client().tryGetRelationsEnforced(qc))
             e["relations_enforced"] = *enforced;
+        // Whether a schema is set, so a UI listing collections does not have to
+        // probe `.../schema` once per collection and read a 404 as an error.
+        // OMITTED, not false, when the database is too old to have schemas at
+        // all: absent means "cannot be determined here", exactly as
+        // `relations_enforced` is omitted rather than defaulted. A plain false
+        // would claim this collection has no schema, which is a different
+        // statement from "this server has no schemas".
+        if (d->db.client().serverSupports(
+                smartbotic::database::Client::Capability::kCollectionSchema))
+            e["has_schema"] = d->db.client().getCollectionSchema(qc).has_value();
         sendJson(res, 200, e);
     });
 

+ 1 - 0
src/server.cpp

@@ -179,6 +179,7 @@ void ApiServer::registerRoutes() {
     registerKeyRoutes(*this);
     registerCollectionRoutes(*this);
     registerIndexRoutes(*this);
+    registerCollectionSchemaRoutes(*this);
     registerDocumentRoutes(*this);
     registerVectorRoutes(*this);
     registerStatsRoutes(*this);

+ 1 - 0
src/server.hpp

@@ -84,6 +84,7 @@ void registerProjectRoutes(ApiServer&);
 void registerKeyRoutes(ApiServer&);
 void registerCollectionRoutes(ApiServer&);
 void registerIndexRoutes(ApiServer&);
+void registerCollectionSchemaRoutes(ApiServer&);
 void registerDocumentRoutes(ApiServer&);
 void registerVectorRoutes(ApiServer&);
 void registerStatsRoutes(ApiServer&);

+ 187 - 0
tests/test_api_integration.cpp

@@ -3820,3 +3820,190 @@ TEST_F(ApiFixture, AStoredSecretIsENCRYPTEDatRest) {
            "effect for this collection. Files:\n"
         << hits;
 }
+
+// --- collection schema (database 2.16.0+) ----------------------------------
+//
+// Skips cleanly on an older database rather than failing: the capability is a
+// property of the server, not of this code, and a red test on a correct
+// deployment is noise that teaches people to ignore the suite.
+namespace {
+bool schemaSupported(svapi::DbGateway& db) {
+    return db.client().serverSupports(
+        smartbotic::database::Client::Capability::kCollectionSchema);
+}
+constexpr const char* kPeopleSchema = R"({
+  "type": "object",
+  "required": ["name", "age"],
+  "additionalProperties": false,
+  "properties": {
+    "name": {"type": "string", "minLength": 1},
+    "age":  {"type": "integer", "minimum": 0},
+    "addr": {"type": "object", "properties": {"zip": {"type": "string"}}}
+  }
+})";
+} // namespace
+
+TEST_F(ApiFixture, SchemaModeDefaultsToEnforceWhenEmptyAndAuditWhenPopulated) {
+    if (!schemaSupported(*db_)) GTEST_SKIP() << "database has no collection_schema capability";
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections/schem_mode";
+    c.Delete(base.c_str());
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                     nlohmann::json{{"name", "schem_mode"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+
+    // EMPTY: enforce, because it cannot fail and a live contract is what the
+    // caller wants.
+    auto put1 = c.Put((base + "/schema").c_str(),
+                      nlohmann::json{{"schema", nlohmann::json::parse(kPeopleSchema)}}.dump(),
+                      "application/json");
+    ASSERT_EQ(put1->status, 200) << put1->body;
+    auto b1 = nlohmann::json::parse(put1->body);
+    EXPECT_EQ(b1.value("mode", ""), "enforce");
+    EXPECT_TRUE(b1.value("mode_defaulted", false));
+
+    // POPULATED and violating: audit, because enforce would refuse and the
+    // COUNTS are what an operator needs first. Defaulting to enforce here
+    // would make the ordinary case look like the feature is broken.
+    ASSERT_EQ(c.Delete((base + "/schema").c_str())->status, 200);
+    ASSERT_EQ(c.Post((base + "/documents").c_str(),
+                     nlohmann::json{{"id", "bad"}, {"name", "X"}, {"age", "not-a-number"}}.dump(),
+                     "application/json")->status, 201);
+    auto put2 = c.Put((base + "/schema").c_str(),
+                      nlohmann::json{{"schema", nlohmann::json::parse(kPeopleSchema)}}.dump(),
+                      "application/json");
+    ASSERT_EQ(put2->status, 200) << put2->body;
+    auto b2 = nlohmann::json::parse(put2->body);
+    EXPECT_EQ(b2.value("mode", ""), "audit");
+    EXPECT_TRUE(b2.value("mode_defaulted", false));
+    EXPECT_GT(b2.value("violating_rows", 0u), 0u) << "audit must report what does not conform";
+
+    // An explicit enforce over the same data REFUSES, with the counts and
+    // examples - the whole value of that answer.
+    auto put3 = c.Put((base + "/schema").c_str(),
+                      nlohmann::json{{"schema", nlohmann::json::parse(kPeopleSchema)},
+                                     {"mode", "enforce"}}.dump(),
+                      "application/json");
+    ASSERT_EQ(put3->status, 422) << put3->body;
+    auto e3 = nlohmann::json::parse(put3->body)["error"];
+    EXPECT_EQ(e3.value("code", ""), "schema_violation");
+    EXPECT_GT(e3["details"].value("violating_rows", 0u), 0u);
+    EXPECT_FALSE(e3["details"]["examples"].empty()) << "a refusal must say WHICH rows";
+    c.Delete(base.c_str());
+}
+
+TEST_F(ApiFixture, SchemaViolationOnAWriteCarriesFieldsAsAnArrayEvenForOnePath) {
+    if (!schemaSupported(*db_)) GTEST_SKIP() << "database has no collection_schema capability";
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections/schem_write";
+    c.Delete(base.c_str());
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                     nlohmann::json{{"name", "schem_write"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Put((base + "/schema").c_str(),
+                    nlohmann::json{{"schema", nlohmann::json::parse(kPeopleSchema)}}.dump(),
+                    "application/json")->status, 200);
+
+    // The slug is mapped in db_errors, NOT in the schema handler, because this
+    // fires on the DOCUMENT routes where callers actually meet it.
+    struct Case { const char* label; nlohmann::json doc; };
+    const std::vector<Case> cases = {
+        {"wrong type",      {{"id", "w1"}, {"name", "A"}, {"age", "x"}}},
+        {"nested path",     {{"id", "w2"}, {"name", "A"}, {"age", 1}, {"addr", {{"zip", 123}}}}},
+        {"missing required",{{"id", "w3"}, {"name", "A"}}},
+        {"extra property",  {{"id", "w4"}, {"name", "A"}, {"age", 1}, {"nope", 1}}},
+        {"two bad paths",   {{"id", "w5"}, {"name", 7}, {"age", "x"}}},
+    };
+    for (const auto& k : cases) {
+        auto res = c.Post((base + "/documents").c_str(), k.doc.dump(), "application/json");
+        ASSERT_TRUE(res) << k.label;
+        ASSERT_EQ(res->status, 422) << k.label << ": " << res->body;
+        auto err = nlohmann::json::parse(res->body)["error"];
+        EXPECT_EQ(err.value("code", ""), "schema_violation") << k.label;
+        // `fields` is ALWAYS an array, including for a single path, and `field`
+        // is never present. The singularising form that `duplicate_values`
+        // uses would make `details.fields.forEach(...)` silently do nothing in
+        // the most common case - a caller would test with a two-error document
+        // and see nothing for one-error ones.
+        ASSERT_TRUE(err.contains("details")) << k.label;
+        EXPECT_TRUE(err["details"]["fields"].is_array()) << k.label << ": " << res->body;
+        EXPECT_FALSE(err["details"].contains("field")) << k.label << ": singular form leaked";
+        EXPECT_FALSE(err["details"]["fields"].empty()) << k.label;
+    }
+
+    // A conforming write still passes, so the schema is not refusing everything.
+    EXPECT_EQ(c.Post((base + "/documents").c_str(),
+                     nlohmann::json{{"id", "good"}, {"name", "A"}, {"age", 30}}.dump(),
+                     "application/json")->status, 201);
+    c.Delete(base.c_str());
+}
+
+TEST_F(ApiFixture, SchemaRoutesRefuseUnknownOptionsAndReportTheirOwnSlugs) {
+    if (!schemaSupported(*db_)) GTEST_SKIP() << "database has no collection_schema capability";
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections/schem_slugs";
+    c.Delete(base.c_str());
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                     nlohmann::json{{"name", "schem_slugs"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+    const nlohmann::json schema = nlohmann::json::parse(kPeopleSchema);
+
+    // No schema yet: 404 with its OWN slug, so a UI can tell "no schema" from
+    // "no such collection" without parsing a sentence.
+    auto none = c.Get((base + "/schema").c_str());
+    ASSERT_EQ(none->status, 404) << none->body;
+    EXPECT_EQ(nlohmann::json::parse(none->body)["error"].value("code", ""), "no_schema");
+
+    // A misspelled option is REFUSED, not ignored - `moed: "audit"` must never
+    // quietly apply the default.
+    auto unk = c.Put((base + "/schema").c_str(),
+                     nlohmann::json{{"schema", schema}, {"moed", "audit"}}.dump(),
+                     "application/json");
+    ASSERT_EQ(unk->status, 422) << unk->body;
+    EXPECT_EQ(nlohmann::json::parse(unk->body)["error"].value("code", ""), "unknown_option");
+
+    // A misspelled MODE is refused rather than defaulted, and names what it got.
+    auto badmode = c.Put((base + "/schema").c_str(),
+                         nlohmann::json{{"schema", schema}, {"mode", "enfroce"}}.dump(),
+                         "application/json");
+    ASSERT_EQ(badmode->status, 422) << badmode->body;
+
+    // A schema outside the supported subset gets `invalid_schema`, NOT
+    // `schema_violation`: one says fix your schema, the other says fix your
+    // data, and folding them would send a caller hunting a typo in a schema
+    // that is correct.
+    auto bad = c.Put((base + "/schema").c_str(),
+                     nlohmann::json{{"schema", {{"type", "nonsense-kind"}}}}.dump(),
+                     "application/json");
+    ASSERT_EQ(bad->status, 422) << bad->body;
+    EXPECT_EQ(nlohmann::json::parse(bad->body)["error"].value("code", ""), "invalid_schema");
+
+    ASSERT_EQ(c.Put((base + "/schema").c_str(),
+                    nlohmann::json{{"schema", schema}}.dump(), "application/json")->status, 200);
+
+    // `has_schema` on the collection GET, so a UI listing collections does not
+    // probe this route once per collection and read a 404 as an error.
+    auto coll = c.Get(base.c_str());
+    ASSERT_EQ(coll->status, 200);
+    EXPECT_TRUE(nlohmann::json::parse(coll->body).value("has_schema", false));
+
+    // suggest NEVER applies: lengths and ranges are described rather than
+    // enforced, so arming it unseen would create something stricter-looking
+    // than what it checks. `applied: false` says so in the payload.
+    auto sug = c.Get((base + "/schema/suggest").c_str());
+    ASSERT_EQ(sug->status, 200) << sug->body;
+    auto sb = nlohmann::json::parse(sug->body);
+    EXPECT_FALSE(sb.value("applied", true));
+    EXPECT_TRUE(sb.contains("complete")) << "emitted unconditionally, so absence means old server";
+    EXPECT_TRUE(sb["schema"].is_object());
+
+    // Drop is idempotent, like the index drop: a second call reaches the same
+    // end state, so it is 200 rather than 404.
+    EXPECT_EQ(c.Delete((base + "/schema").c_str())->status, 200);
+    EXPECT_EQ(c.Delete((base + "/schema").c_str())->status, 200);
+    // And with the schema gone, the write it refused now succeeds.
+    EXPECT_EQ(c.Post((base + "/documents").c_str(),
+                     nlohmann::json{{"id", "free"}, {"name", "A"}, {"age", "x"}}.dump(),
+                     "application/json")->status, 201);
+    c.Delete(base.c_str());
+}