database.proto 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. // Smartbotic Database Service
  2. // Document-oriented storage with persistence and replication
  3. syntax = "proto3";
  4. package smartbotic.databasepb;
  5. // Error code range: 6000-6999 for Database errors
  6. // 6000: Generic database error
  7. // 6001: Collection not found
  8. // 6002: Document not found
  9. // 6003: Document already exists
  10. // 6004: Version conflict
  11. // 6005: Invalid query
  12. // 6006: File not found
  13. // 6007: File too large
  14. // 6008: Encryption error
  15. // 6009: Replication error
  16. // 6010: Version not found
  17. // ===== Main Database Service =====
  18. // v2.12.0 - REFUSAL DETAIL. Any refused write may carry trailing metadata
  19. // `sbdb-error-detail-bin`: UTF-8 JSON (gRPC base64s a -bin value on the wire)
  20. // that says WHY in a form a program can branch on, whether the refusal came as
  21. // an error status or in-band (status OK, success=false). Keys, all optional:
  22. //
  23. // reason "unique_violation" | "missing_parent" | "delete_restricted"
  24. // | "read_only" | "memory_pressure" | "view_write"
  25. // | "not_found" | "version_conflict" | "invalid_increment"
  26. // | "duplicate_id" (2.12.1) | "file_too_large"
  27. // | "mime_type_not_allowed" (2.12.3)
  28. // code the gRPC status code number - present for in-band
  29. // refusals, whose status is OK
  30. // fields the field(s) concerned: the constrained field(s) of a
  31. // unique violation, the reference field of a missing
  32. // parent, the field an increment could not be applied to
  33. // values object, field -> the value that collided / was refused
  34. // conflicting_id unique violation: the document already holding the value
  35. // relation missing parent: the relation that refused the write
  36. // current_version version conflict: the document's current version
  37. //
  38. // Absent on a server older than 2.12.0. The reason exists because a status
  39. // code alone is ambiguous: FAILED_PRECONDITION means a missing parent, a
  40. // restricted delete AND read-only mode.
  41. service DatabaseService {
  42. // Document operations
  43. rpc Insert(InsertRequest) returns (InsertResponse);
  44. rpc Get(GetRequest) returns (GetResponse);
  45. rpc Update(UpdateRequest) returns (UpdateResponse);
  46. rpc Upsert(UpsertRequest) returns (UpsertResponse);
  47. rpc Delete(DeleteRequest) returns (DeleteResponse);
  48. rpc PatchDocument(PatchDocumentRequest) returns (PatchDocumentResponse);
  49. rpc Exists(ExistsRequest) returns (ExistsResponse);
  50. // Version history operations
  51. rpc GetVersionHistory(GetVersionHistoryRequest) returns (GetVersionHistoryResponse);
  52. rpc GetDocumentVersion(GetDocumentVersionRequest) returns (GetDocumentVersionResponse);
  53. rpc RestoreVersion(RestoreVersionRequest) returns (RestoreVersionResponse);
  54. rpc RestoreToDate(RestoreToDateRequest) returns (RestoreToDateResponse);
  55. // Batch operations
  56. rpc BatchInsert(BatchInsertRequest) returns (BatchInsertResponse);
  57. rpc BatchGet(BatchGetRequest) returns (BatchGetResponse);
  58. rpc BatchDelete(BatchDeleteRequest) returns (BatchDeleteResponse);
  59. // Query operations
  60. rpc Find(FindRequest) returns (FindResponse);
  61. rpc Count(CountRequest) returns (CountResponse);
  62. rpc SimilaritySearch(SimilaritySearchRequest) returns (SimilaritySearchResponse);
  63. // v2.13.0 - stream one collection out, documents plus (optionally) their
  64. // stored vectors. See ExportRequest for the contract.
  65. rpc ExportCollection(ExportRequest) returns (stream ExportChunk);
  66. // Set operations (Redis compatibility)
  67. rpc SetAdd(SetAddRequest) returns (SetAddResponse);
  68. rpc SetRemove(SetRemoveRequest) returns (SetRemoveResponse);
  69. rpc SetMembers(SetMembersRequest) returns (SetMembersResponse);
  70. rpc SetIsMember(SetIsMemberRequest) returns (SetIsMemberResponse);
  71. // Collection management
  72. rpc CreateCollection(CreateCollectionRequest) returns (CreateCollectionResponse);
  73. rpc DropCollection(DropCollectionRequest) returns (DropCollectionResponse);
  74. rpc ListCollections(ListCollectionsRequest) returns (ListCollectionsResponse);
  75. rpc GetCollectionInfo(GetCollectionInfoRequest) returns (GetCollectionInfoResponse);
  76. // v2.3 — Project management. Projects are top-level namespaces over
  77. // collections. The "default" project is implicit and always exists.
  78. rpc ListProjects(ListProjectsRequest) returns (ListProjectsResponse);
  79. rpc CreateProject(CreateProjectRequest) returns (CreateProjectResponse);
  80. rpc DropProject(DropProjectRequest) returns (DropProjectResponse);
  81. // View management
  82. rpc CreateView(CreateViewRequest) returns (CreateViewResponse);
  83. rpc DropView(DropViewRequest) returns (DropViewResponse);
  84. rpc ListViews(ListViewsRequest) returns (ListViewsResponse);
  85. rpc GetViewInfo(GetViewInfoRequest) returns (GetViewInfoResponse);
  86. // v2.11.0 T6b — relation (referential integrity) management. Admin-only:
  87. // `_relations` is a system collection and a relation names another
  88. // collection's schema, so declaring one is not ordinary per-collection
  89. // write access.
  90. rpc CreateRelation(CreateRelationRequest) returns (CreateRelationResponse);
  91. rpc DropRelation(DropRelationRequest) returns (DropRelationResponse);
  92. rpc ListRelations(ListRelationsRequest) returns (ListRelationsResponse);
  93. rpc GetRelationInfo(GetRelationInfoRequest) returns (GetRelationInfoResponse);
  94. // v2.11.0 T5 — "what would happen if I deleted this?" without deleting
  95. // it. Read-only and gated as an ordinary per-collection read, not admin.
  96. rpc DescribeDelete(DescribeDeleteRequest) returns (DescribeDeleteResponse);
  97. // v2.11.0 T7 — "does this relation's reverse index actually match live
  98. // data?" A relation declared over a collection that already had rows
  99. // before v2.11.0 T7 shipped (or one whose sub-db was lost/restored from
  100. // an older snapshot) can carry postings for parent ids that no longer
  101. // exist. This walks the reverse index and probes each parent id;
  102. // mutates nothing. ⚠ Cost is proportional to the number of DISTINCT
  103. // parents referenced, not collection size, but on a very large child
  104. // collection that is still a full index walk - treat this as an
  105. // operator/migration tool, not something to call on a hot path.
  106. // Admin-only, like the other relation-management RPCs above (NOT gated
  107. // as a per-collection read on `child`, despite being read-only and
  108. // reporting facts about that collection's data): answering requires
  109. // resolving the relation first to learn its `child`, and gating after
  110. // that lookup would make a nonexistent-relation response distinguishable
  111. // from an existing-but-unauthorized one - a probe-able existence oracle,
  112. // which is exactly what gate() exists to prevent elsewhere.
  113. rpc CheckRelation(CheckRelationRequest) returns (CheckRelationResponse);
  114. // Collection configuration
  115. rpc ConfigureCollection(ConfigureCollectionRequest) returns (ConfigureCollectionResponse);
  116. // v2.9.0 — secondary indexes. Declaration is explicit per collection: an
  117. // index costs write throughput, and indexing every field would build useless
  118. // ones (a low-cardinality field like a status enum is slower through an
  119. // index than a scan).
  120. rpc CreateIndex(CreateIndexRequest) returns (CreateIndexResponse);
  121. // v2.16.0 - per-collection JSON Schema: every write's resulting document
  122. // must conform (enforce) or is logged and counted (audit).
  123. rpc SetCollectionSchema(SetCollectionSchemaRequest) returns (SetCollectionSchemaResponse);
  124. rpc GetCollectionSchema(GetCollectionSchemaRequest) returns (GetCollectionSchemaResponse);
  125. rpc SuggestCollectionSchema(SuggestCollectionSchemaRequest) returns (SuggestCollectionSchemaResponse);
  126. rpc DropIndex(DropIndexRequest) returns (DropIndexResponse);
  127. rpc ListIndexes(ListIndexesRequest) returns (ListIndexesResponse);
  128. // v2.10.0 — the distinct values an indexed field holds, with row counts.
  129. // Answered from the index, one step per distinct value rather than per row.
  130. rpc GetIndexValues(GetIndexValuesRequest) returns (GetIndexValuesResponse);
  131. rpc GetCollectionConfig(GetCollectionConfigRequest) returns (GetCollectionConfigResponse);
  132. rpc MigrateCollectionTimestamps(MigrateCollectionTimestampsRequest) returns (MigrateCollectionTimestampsResponse);
  133. // File operations
  134. rpc UploadFile(stream FileChunk) returns (UploadFileResponse);
  135. rpc DownloadFile(DownloadFileRequest) returns (stream FileChunk);
  136. rpc DeleteFile(DeleteFileRequest) returns (DeleteFileResponse);
  137. rpc GetFileInfo(GetFileInfoRequest) returns (FileInfo);
  138. rpc ListFiles(ListFilesRequest) returns (ListFilesResponse);
  139. rpc SetFileTtl(SetFileTtlRequest) returns (SetFileTtlResponse);
  140. // Event subscription
  141. rpc Subscribe(SubscribeRequest) returns (stream DatabaseEvent);
  142. // Health and stats
  143. rpc HealthCheck(HealthCheckRequest) returns (HealthCheckResponse);
  144. // v2.15.0 - what this server is and which features it has, so a client can
  145. // refuse a call the server would misunderstand instead of sending it. A
  146. // pre-2.15.0 server answers UNIMPLEMENTED.
  147. rpc GetServerInfo(GetServerInfoRequest) returns (GetServerInfoResponse);
  148. // v2.17.0 - audit encryption at rest: every stored row and history
  149. // version, counted against the encryption rules. Read-only, admin.
  150. rpc VerifyEncryption(VerifyEncryptionRequest) returns (VerifyEncryptionResponse);
  151. rpc GetStats(GetStatsRequest) returns (GetStatsResponse);
  152. rpc GetMemoryStats(GetMemoryStatsRequest) returns (GetMemoryStatsResponse);
  153. // Read-only runtime state control
  154. rpc SetReadOnly(SetReadOnlyRequest) returns (SetReadOnlyResponse);
  155. rpc GetReadOnlyStatus(GetReadOnlyStatusRequest) returns (GetReadOnlyStatusResponse);
  156. }
  157. // ===== Replication Service =====
  158. service DatabaseReplication {
  159. // Bidirectional streaming for real-time sync
  160. rpc SyncStream(stream ReplicationMessage) returns (stream ReplicationMessage);
  161. // Pull missed entries (for recovery)
  162. rpc GetEntriesSince(GetEntriesRequest) returns (stream ReplicationEntry);
  163. // Get current node state
  164. rpc GetNodeState(GetNodeStateRequest) returns (NodeState);
  165. }
  166. // ===== Document Types =====
  167. message Document {
  168. string id = 1;
  169. string collection = 2;
  170. bytes data = 3; // JSON-encoded document data
  171. uint64 version = 4;
  172. uint64 created_at = 5; // Timestamp in milliseconds
  173. uint64 updated_at = 6;
  174. uint64 expires_at = 7; // 0 = no expiration
  175. string node_id = 8; // Origin node for replication
  176. bool encrypted = 9;
  177. repeated string encrypted_fields = 10;
  178. string created_by = 11; // User ID who created the document
  179. string updated_by = 12; // User ID who last updated the document
  180. // v2.13.0 - the stored vector as raw float32 little-endian bytes. Set ONLY
  181. // when the request asked for vectors (GetRequest/FindRequest
  182. // include_vector, ExportRequest include_vectors) and a vector is stored.
  183. bytes vector = 13;
  184. }
  185. // ===== Document Operations =====
  186. message InsertRequest {
  187. string collection = 1;
  188. bytes data = 2; // JSON document
  189. string id = 3; // Optional, auto-generated if empty
  190. uint32 ttl_seconds = 4; // 0 = use collection default
  191. string actor = 5; // User ID performing the operation (for audit)
  192. }
  193. message InsertResponse {
  194. string id = 1;
  195. uint64 version = 2;
  196. }
  197. message GetRequest {
  198. string collection = 1;
  199. string id = 2;
  200. bool include_vector = 3; // v2.13.0 - fill Document.vector
  201. }
  202. message GetResponse {
  203. Document document = 1;
  204. bool found = 2;
  205. }
  206. message UpdateRequest {
  207. string collection = 1;
  208. string id = 2;
  209. bytes data = 3;
  210. uint64 expected_version = 4; // 0 = no version check (force update)
  211. string actor = 5; // User ID performing the operation (for audit)
  212. // v2.8.0 — change the document's expiry as part of the update.
  213. //
  214. // `optional` gives three distinct meanings, which a plain uint32 cannot:
  215. // absent -> leave the existing expiry alone (the default, and what an
  216. // update did implicitly once it stopped WIPING the expiry)
  217. // 0 -> clear the expiry: the document becomes permanent
  218. // N -> expire N seconds from now
  219. //
  220. // Before this, ttl_seconds existed only on Insert/Upsert/BatchInsert, so
  221. // changing a TTL meant rewriting the whole document via upsert.
  222. optional uint32 ttl_seconds = 6;
  223. }
  224. message UpdateResponse {
  225. uint64 new_version = 1;
  226. bool success = 2;
  227. string error = 3;
  228. // v2.12.0 - when success=false, the gRPC status code this refusal WOULD
  229. // carry: NOT_FOUND, ABORTED (version conflict), FAILED_PRECONDITION
  230. // (read-only), RESOURCE_EXHAUSTED (memory pressure), INVALID_ARGUMENT
  231. // (write to a view). These refusals stay in-band (status OK) so clients
  232. // older than 2.12.0 see exactly what they always saw; 0 from an older
  233. // server. The trailing `sbdb-error-detail-bin` adds the reason.
  234. int32 error_code = 4;
  235. }
  236. message UpsertRequest {
  237. string collection = 1;
  238. bytes data = 2;
  239. string id = 3;
  240. uint32 ttl_seconds = 4;
  241. string actor = 5; // User ID performing the operation (for audit)
  242. }
  243. message UpsertResponse {
  244. string id = 1;
  245. uint64 version = 2;
  246. bool inserted = 3; // true if inserted, false if updated
  247. }
  248. message DeleteRequest {
  249. string collection = 1;
  250. string id = 2;
  251. // v2.12.0 - who is deleting, as `actor` is on every other write. Reported
  252. // on the resulting DatabaseEvent (and on the events of any documents a
  253. // relation cascade deletes or nulls because of it). Not stored: the
  254. // document is gone, and its last version in history keeps the updated_by
  255. // of whoever last WROTE it, which is not who deleted it.
  256. string actor = 3;
  257. }
  258. message DeleteResponse {
  259. bool deleted = 1;
  260. }
  261. message PatchDocumentRequest {
  262. string collection = 1;
  263. string id = 2;
  264. bytes patch_json = 3; // JSON fields to merge into existing document
  265. string actor = 4; // User ID performing the operation (for audit)
  266. // v2.8.0 — same three-way semantics as UpdateRequest.ttl_seconds: absent
  267. // leaves the expiry alone, 0 clears it, N sets N seconds from now.
  268. optional uint32 ttl_seconds = 5;
  269. // v2.12.0 - apply only if the document is still at this version: a
  270. // conditional PARTIAL update. updateIfVersion replaces the whole body, so a
  271. // caller that only wants to change one field ("claim this task") would
  272. // have to write back everything it read, reverting any field a concurrent
  273. // writer changed meanwhile. A mismatch is refused with status ABORTED,
  274. // reason "version_conflict" and the current version in the detail.
  275. // Absent = unconditional, as before.
  276. optional uint64 expected_version = 6;
  277. // v2.12.0 - ATOMIC INCREMENT. A JSON object of field -> number to add, in
  278. // the same locked read-modify-write as the merge, so concurrent increments
  279. // never lose an update. Dotted paths descend objects (creating them).
  280. // - an absent or null field counts as 0;
  281. // - integer + integer stays an integer (overflow is refused), anything
  282. // else is a double;
  283. // - a non-numeric stored value, a non-numeric delta, or a field that
  284. // patch_json also sets is refused with INVALID_ARGUMENT, reason
  285. // "invalid_increment", and the field in the detail.
  286. // Nothing is written when any increment is refused. patch_json may be
  287. // empty when only incrementing. The new values come back in
  288. // PatchDocumentResponse.incremented_json.
  289. bytes increments_json = 7;
  290. }
  291. message PatchDocumentResponse {
  292. uint64 new_version = 1;
  293. bool success = 2;
  294. string error = 3;
  295. // v2.12.0 - as UpdateResponse.error_code.
  296. int32 error_code = 4;
  297. // v2.12.0 - JSON object, field -> value AFTER the increments, for every
  298. // field in increments_json. Empty when there were none.
  299. bytes incremented_json = 5;
  300. }
  301. message ExistsRequest {
  302. string collection = 1;
  303. string id = 2;
  304. }
  305. message ExistsResponse {
  306. bool exists = 1;
  307. }
  308. // ===== Version History Operations =====
  309. message DocumentVersionEntry {
  310. uint64 version = 1;
  311. bytes data = 2; // JSON-encoded document data at this version
  312. uint64 timestamp = 3; // When this version was created (updatedAt)
  313. string updated_by = 4;
  314. bool encrypted = 5;
  315. repeated string encrypted_fields = 6;
  316. }
  317. message GetVersionHistoryRequest {
  318. string collection = 1;
  319. string id = 2;
  320. uint32 limit = 3; // 0 = all versions
  321. uint32 offset = 4;
  322. }
  323. message GetVersionHistoryResponse {
  324. repeated DocumentVersionEntry versions = 1;
  325. uint64 current_version = 2; // 0 if document is deleted
  326. uint64 total_count = 3;
  327. bool document_deleted = 4;
  328. }
  329. message GetDocumentVersionRequest {
  330. string collection = 1;
  331. string id = 2;
  332. uint64 version = 3;
  333. }
  334. message GetDocumentVersionResponse {
  335. DocumentVersionEntry version_entry = 1;
  336. bool found = 2;
  337. }
  338. message RestoreVersionRequest {
  339. string collection = 1;
  340. string id = 2;
  341. uint64 version = 3; // Version number to restore
  342. string actor = 4; // User performing the restore
  343. }
  344. message RestoreVersionResponse {
  345. uint64 new_version = 1; // The newly created version number
  346. bool success = 2;
  347. string error = 3;
  348. }
  349. message RestoreToDateRequest {
  350. string collection = 1;
  351. string id = 2;
  352. uint64 timestamp = 3; // Find version active at this time (ms since epoch)
  353. string actor = 4;
  354. }
  355. message RestoreToDateResponse {
  356. uint64 restored_version = 1; // Which old version was restored from
  357. uint64 new_version = 2; // The newly created version number
  358. bool success = 3;
  359. string error = 4;
  360. }
  361. // ===== Batch Operations =====
  362. message BatchInsertRequest {
  363. string collection = 1;
  364. repeated BatchInsertItem items = 2;
  365. string actor = 3; // User ID performing the operation (for audit)
  366. }
  367. message BatchInsertItem {
  368. bytes data = 1;
  369. string id = 2;
  370. uint32 ttl_seconds = 3;
  371. }
  372. message BatchInsertResponse {
  373. repeated string ids = 1;
  374. uint32 success_count = 2;
  375. uint32 error_count = 3;
  376. }
  377. message BatchGetRequest {
  378. string collection = 1;
  379. repeated string ids = 2;
  380. }
  381. message BatchGetResponse {
  382. repeated Document documents = 1;
  383. }
  384. message BatchDeleteRequest {
  385. string collection = 1;
  386. repeated string ids = 2;
  387. string actor = 3; // v2.12.0 - as DeleteRequest.actor, for every id
  388. }
  389. message BatchDeleteResponse {
  390. uint64 deleted_count = 1;
  391. // v2.12.0 - the ids actually deleted, in request order. An id that is
  392. // absent here did not exist. If the call fails partway (a relation
  393. // refuses one id), the status is an error and no response is delivered:
  394. // ids before it may already be gone - re-read to learn which.
  395. repeated string deleted_ids = 2;
  396. }
  397. // ===== Query Operations =====
  398. message FindRequest {
  399. string collection = 1;
  400. repeated Filter filters = 2;
  401. Sort sort = 3;
  402. uint32 limit = 4; // Default 100
  403. uint32 offset = 5;
  404. repeated string projection = 6; // Fields to include (empty = all)
  405. bool include_vector = 7; // v2.13.0 - fill Document.vector on each result
  406. }
  407. message Filter {
  408. string field = 1;
  409. FilterOp op = 2;
  410. bytes value = 3; // JSON-encoded value
  411. }
  412. enum FilterOp {
  413. FILTER_OP_UNSPECIFIED = 0;
  414. FILTER_OP_EQ = 1;
  415. FILTER_OP_NE = 2;
  416. FILTER_OP_GT = 3;
  417. FILTER_OP_GTE = 4;
  418. FILTER_OP_LT = 5;
  419. FILTER_OP_LTE = 6;
  420. FILTER_OP_IN = 7;
  421. FILTER_OP_CONTAINS = 8;
  422. FILTER_OP_EXISTS = 9;
  423. FILTER_OP_REGEX = 10;
  424. FILTER_OP_SEARCH = 11; // Full-text search across ID and string fields
  425. }
  426. message Sort {
  427. string field = 1;
  428. bool descending = 2;
  429. }
  430. message FindResponse {
  431. repeated Document documents = 1;
  432. uint64 total_count = 2;
  433. bool has_more = 3;
  434. // WAL fallback metrics (for queries that include evicted documents)
  435. bool used_wal_fallback = 4; // True if WAL was scanned for evicted docs
  436. uint32 memory_match_count = 5; // Documents matched from memory
  437. uint32 wal_match_count = 6; // Documents matched from WAL
  438. uint64 memory_search_micros = 7; // Time spent searching memory (µs)
  439. uint64 wal_search_micros = 8; // Time spent loading/searching WAL (µs)
  440. }
  441. message CountRequest {
  442. string collection = 1;
  443. repeated Filter filters = 2;
  444. }
  445. message CountResponse {
  446. uint64 count = 1;
  447. }
  448. // ===== Export (v2.13.0) =====
  449. //
  450. // One collection, never a project: the unit is a collection named exactly as
  451. // every other call names one, so a caller whose tenancy is a collection-name
  452. // prefix cannot be handed another tenant's rows. Gated as an ordinary READ of
  453. // that collection (column masks and row predicates apply), not admin.
  454. //
  455. // The stream is: one header, then row batches, then one trailer.
  456. // - One stream is one LMDB read transaction: an exact snapshot, rows in id
  457. // order, none skipped or repeated. header.rows_at_snapshot counts the rows
  458. // the stream will send if it completes, so rows_sent == rows_at_snapshot
  459. // checks it.
  460. // - Resuming with after_id = trailer.last_id starts a NEW snapshot strictly
  461. // after that id: it never repeats a row, but can miss one inserted during
  462. // the gap with an id that sorts before the cursor.
  463. // - A stream ends early (complete=false, last_id set) when it reaches the
  464. // server's time cap (header.max_stream_seconds) - that is the resume case.
  465. // - A row larger than the server's send limit ends the stream with
  466. // RESOURCE_EXHAUSTED, reason row_too_large, conflicting_id = that row; the
  467. // rows before it were sent. It is never skipped silently.
  468. // - A stream that ends without a trailer did not complete. Treat it as
  469. // failed; a client must never read a stream without a trailer as whole.
  470. // - A restored row gets FRESH metadata: insert stamps _created_at,
  471. // _updated_at, _version and _created_by itself. The originals are in each
  472. // exported Document; keep them there, or copy them into your own field
  473. // before importing if you need them as data.
  474. message ExportRequest {
  475. string collection = 1;
  476. // Include each row's vector (Document.vector) and its vector_state.
  477. // Refused with INVALID_ARGUMENT (reason no_vector_index) on a collection
  478. // with vector_dimension 0, which cannot hold vectors.
  479. bool include_vectors = 2;
  480. string after_id = 3; // resume cursor; empty = from the start
  481. uint32 batch_rows = 4; // rows per ExportRows; 0 = default; clamped, never refused
  482. }
  483. enum VectorState {
  484. VECTOR_STATE_UNSPECIFIED = 0; // include_vectors was false
  485. VECTOR_STATE_PRESENT = 1; // vector stored; Document.vector holds it
  486. VECTOR_STATE_NONE = 2; // written without a vector
  487. VECTOR_STATE_MISSING = 3; // written WITH a vector, and its entry is gone
  488. VECTOR_STATE_UNKNOWN = 4; // no entry, and the row predates the marker (pre-2.13.0)
  489. }
  490. message ExportHeader {
  491. string collection = 1;
  492. uint32 vector_dimension = 2;
  493. string vector_dtype = 3; // "float32-le"
  494. uint64 rows_at_snapshot = 4;
  495. uint32 batch_rows_cap = 5; // the most rows a batch holds (requested, clamped); a batch also closes at 8 MB, so it may hold fewer
  496. uint32 max_stream_seconds = 6;
  497. }
  498. message ExportRow {
  499. Document document = 1; // same shape as a Get result
  500. VectorState vector_state = 2;
  501. }
  502. message ExportRows {
  503. repeated ExportRow rows = 1;
  504. }
  505. message ExportTrailer {
  506. uint64 rows_sent = 1;
  507. string last_id = 2; // id of the last row sent; the resume cursor
  508. bool complete = 3; // true only when the end of the collection was reached
  509. }
  510. message ExportChunk {
  511. oneof chunk {
  512. ExportHeader header = 1;
  513. ExportRows rows = 2;
  514. ExportTrailer trailer = 3;
  515. }
  516. }
  517. message SimilaritySearchRequest {
  518. string collection = 1;
  519. repeated float query_vector = 2;
  520. uint32 top_k = 3;
  521. float min_score = 4;
  522. // v2.14.0 - only rows matching EVERY filter are candidates (same grammar
  523. // and semantics as FindRequest.filters). The answer is the exact top-K
  524. // among matching rows; min_score then trims. A pre-2.14.0 server ignores
  525. // this field and answers UNFILTERED, which is why the response says
  526. // whether the filters were applied.
  527. repeated Filter filters = 5;
  528. }
  529. message SimilaritySearchResponse {
  530. repeated SimilarityResult results = 1;
  531. // v2.14.0 - true when the server applied `filters`. A pre-2.14.0 server
  532. // never sets it, so a client that sent filters and reads false must NOT
  533. // use the results: they are unfiltered.
  534. bool filters_applied = 2;
  535. }
  536. message SimilarityResult {
  537. string id = 1;
  538. float score = 2;
  539. bytes data = 3;
  540. }
  541. // ===== Set Operations =====
  542. message SetAddRequest {
  543. string collection = 1;
  544. string set_id = 2;
  545. string member = 3;
  546. }
  547. message SetAddResponse {
  548. bool added = 1; // false if already exists
  549. }
  550. message SetRemoveRequest {
  551. string collection = 1;
  552. string set_id = 2;
  553. string member = 3;
  554. }
  555. message SetRemoveResponse {
  556. bool removed = 1;
  557. }
  558. message SetMembersRequest {
  559. string collection = 1;
  560. string set_id = 2;
  561. }
  562. message SetMembersResponse {
  563. repeated string members = 1;
  564. }
  565. message SetIsMemberRequest {
  566. string collection = 1;
  567. string set_id = 2;
  568. string member = 3;
  569. }
  570. message SetIsMemberResponse {
  571. bool is_member = 1;
  572. }
  573. // ===== Collection Management =====
  574. message CreateCollectionRequest {
  575. string name = 1;
  576. CollectionOptions options = 2;
  577. }
  578. message CollectionOptions {
  579. bool auto_create_id = 1;
  580. uint32 default_ttl_seconds = 2;
  581. bool encrypted = 3;
  582. repeated string sensitive_fields = 4;
  583. uint32 max_versions = 5; // Max version history per document (0 = unlimited)
  584. uint32 vector_dimension = 6; // Dimension of vectors stored in this collection (0 = not a vector collection)
  585. // NEW in v1.7.0 — eviction priority for the collection.
  586. // UNSPECIFIED is treated as NORMAL for backward compatibility.
  587. MemoryPriority memory_priority = 7;
  588. }
  589. enum MemoryPriority {
  590. MEMORY_PRIORITY_UNSPECIFIED = 0; // treated as NORMAL
  591. MEMORY_PRIORITY_LOW = 1;
  592. MEMORY_PRIORITY_NORMAL = 2;
  593. MEMORY_PRIORITY_HIGH = 3;
  594. }
  595. message CreateCollectionResponse {
  596. bool created = 1;
  597. }
  598. message DropCollectionRequest {
  599. string name = 1;
  600. }
  601. message DropCollectionResponse {
  602. bool dropped = 1;
  603. }
  604. message ListCollectionsRequest {
  605. // v2.8.0 — restrict the listing to one project namespace, mirroring
  606. // ListViewsRequest. Empty lists every project (operator/CLI use); clients
  607. // always set it, so a workspace never sees another workspace's collection
  608. // names. A collection name is information about the shape of someone else's
  609. // data even when its contents are unreachable.
  610. string project = 1;
  611. }
  612. message ListCollectionsResponse {
  613. repeated string names = 1;
  614. }
  615. message GetCollectionInfoRequest {
  616. string name = 1;
  617. }
  618. message GetCollectionInfoResponse {
  619. CollectionInfo info = 1;
  620. bool found = 2;
  621. }
  622. // What a collection IS: its creation-time options and its size.
  623. //
  624. // Settings changeable after creation are NOT here - timestamp_precision,
  625. // versioning_enabled and relations_enforced are read with GetCollectionConfig
  626. // (see CollectionConfig), which always populates all three on a reply. Their
  627. // absence from this message does not mean they cannot be read.
  628. message CollectionInfo {
  629. string name = 1;
  630. uint64 document_count = 2;
  631. uint64 size_bytes = 3;
  632. CollectionOptions options = 4;
  633. uint64 created_at = 5;
  634. uint64 updated_at = 6;
  635. uint32 vector_dimension = 7; // Dimension of vectors stored in this collection (0 = not a vector collection)
  636. }
  637. // ===== Project Management (v2.3) =====
  638. //
  639. // Projects are top-level namespaces over collections. Collections live
  640. // inside a project; wire-form "my_app:users" addresses collection "users"
  641. // in project "my_app", bare "users" addresses ("default", "users"). The
  642. // "default" project is implicit and always present.
  643. //
  644. // Stage F ships the RPC surface backed by a filesystem-only placeholder
  645. // (`<dataDir>/projects/<name>/env/`). Stage B replaces the placeholder
  646. // with the real ProjectStore-backed implementation.
  647. message ListProjectsRequest {}
  648. message ListProjectsResponse {
  649. // Alphabetical. Always includes "default".
  650. repeated string projects = 1;
  651. }
  652. message CreateProjectRequest {
  653. string name = 1;
  654. }
  655. message CreateProjectResponse {
  656. // true = newly created, false = already existed (idempotent) OR validation error.
  657. bool created = 1;
  658. // Populated on validation failure (e.g. invalid name). Empty on success
  659. // and on the idempotent "already existed" path.
  660. string error = 2;
  661. }
  662. message DropProjectRequest {
  663. string name = 1;
  664. }
  665. message DropProjectResponse {
  666. bool dropped = 1;
  667. // Populated when the drop is refused — e.g. name == "default",
  668. // unknown project, or filesystem error.
  669. string error = 2;
  670. }
  671. // ===== File Operations =====
  672. message FileChunk {
  673. oneof content {
  674. FileMetadata metadata = 1; // First chunk includes metadata
  675. bytes data = 2; // Subsequent chunks are data
  676. }
  677. }
  678. message FileMetadata {
  679. string id = 1; // Set by server on upload response
  680. string name = 2;
  681. string mime_type = 3;
  682. uint64 size = 4;
  683. string file_type = 5; // "plugin", "document", "generated"
  684. string related_id = 6; // plugin_id, conversation_id, etc.
  685. map<string, string> metadata = 7; // Custom metadata
  686. bool is_public = 8; // Visibility flag
  687. // v2.6.0 — owning project. Empty means "default", matching the rule for
  688. // bare collection names. Files are namespaced so that per-project access
  689. // policy has something to attach to.
  690. string project = 9;
  691. // v2.8.0 — relative time-to-live in seconds, applied at upload. Converted
  692. // once to an absolute expiry server-side, so a file's lifetime does not
  693. // restart when it is read or on restart.
  694. //
  695. // `optional` is load-bearing: ABSENT means "inherit the configured default
  696. // for this file type", while an explicitly SET 0 means "never expire" and
  697. // overrides that default. A plain uint32 cannot express the difference,
  698. // which would make it impossible to opt one file out of a retention policy.
  699. optional uint32 ttl_seconds = 10;
  700. }
  701. message UploadFileResponse {
  702. string id = 1;
  703. uint64 size = 2;
  704. string checksum = 3; // SHA-256
  705. bool deduplicated = 4; // True if blob already existed
  706. }
  707. message DownloadFileRequest {
  708. string id = 1;
  709. string project = 2; // v2.6.0 — empty means "default"
  710. }
  711. message DeleteFileRequest {
  712. string id = 1;
  713. string project = 2; // v2.6.0 — empty means "default"
  714. }
  715. message DeleteFileResponse {
  716. bool deleted = 1;
  717. }
  718. message GetFileInfoRequest {
  719. string id = 1;
  720. string project = 2; // v2.6.0 — empty means "default"
  721. }
  722. message FileInfo {
  723. string id = 1;
  724. string name = 2;
  725. string mime_type = 3;
  726. uint64 size = 4;
  727. string file_type = 5;
  728. string related_id = 6;
  729. string checksum = 7;
  730. uint64 created_at = 8;
  731. map<string, string> metadata = 9;
  732. bool is_public = 10; // Visibility flag
  733. uint32 ref_count = 11; // Blob reference count (informational)
  734. string project = 12; // v2.6.0 — owning project
  735. uint64 expires_at = 13; // v2.8.0 — absolute expiry ms, 0 = never
  736. }
  737. message ListFilesRequest {
  738. string file_type = 1; // Filter by type (optional)
  739. string related_id = 2; // Filter by related ID (optional)
  740. uint32 limit = 3;
  741. uint32 offset = 4;
  742. string checksum = 5; // Filter by checksum (for dedup queries)
  743. string name = 6; // Filter by exact filename (optional)
  744. string project = 7; // v2.6.0 — empty means "default"
  745. }
  746. // v2.8.0 — change the expiry of a file that is already stored. A file's TTL was
  747. // otherwise fixed at upload.
  748. message SetFileTtlRequest {
  749. string id = 1;
  750. string project = 2; // empty means "default"
  751. // Absent is invalid here - the call exists to change the expiry, so it must
  752. // say what to. 0 clears the expiry (keep indefinitely); N expires the file N
  753. // seconds from now.
  754. uint32 ttl_seconds = 3;
  755. }
  756. message SetFileTtlResponse {
  757. bool updated = 1; // false if no such file in that project
  758. uint64 expires_at = 2; // the resulting absolute expiry, 0 = never
  759. }
  760. message ListFilesResponse {
  761. repeated FileInfo files = 1;
  762. uint64 total_count = 2;
  763. bool has_more = 3;
  764. }
  765. // ===== Event Subscription =====
  766. message SubscribeRequest {
  767. repeated string collections = 1; // Empty = all collections
  768. repeated string patterns = 2; // Glob patterns (e.g., "assistants:*")
  769. bool include_data = 3; // Include document data in events
  770. }
  771. message DatabaseEvent {
  772. EventType type = 1;
  773. string collection = 2;
  774. string document_id = 3;
  775. uint64 timestamp = 4;
  776. string node_id = 5;
  777. bytes data = 6; // JSON document (if include_data)
  778. // v2.12.0 - who caused this change: the `actor` the write or delete
  779. // request carried. Empty when the request carried none, and for changes
  780. // the database makes itself (TTL expiry). Sent whether or not
  781. // include_data is set.
  782. //
  783. // For a document a relation cascade deleted or nulled, it is the actor of
  784. // the delete that triggered the cascade - the cascade is that caller's
  785. // doing, not whoever last wrote the child.
  786. //
  787. // This is what makes a write-triggered-write loop guard possible: a
  788. // subscriber that reacts to events by writing can tag its own writes and
  789. // recognise them here. Before this an event said nothing about its
  790. // origin; insert/update provenance had to be read back from version
  791. // history after the fact (racing any later write), and a delete's was not
  792. // recorded anywhere.
  793. string actor = 7;
  794. }
  795. enum EventType {
  796. EVENT_UNKNOWN = 0;
  797. EVENT_INSERT = 1;
  798. EVENT_UPDATE = 2;
  799. EVENT_DELETE = 3;
  800. EVENT_EXPIRE = 4;
  801. EVENT_INVALIDATE = 5;
  802. // NEW in v1.7.0 — memory-pressure observability events.
  803. EVENT_MEMORY_PRESSURE_HIGH = 6; // Emitted when pressure reaches hard threshold
  804. EVENT_MEMORY_EVICTION_BURST = 7; // Emitted when eviction runs a large burst
  805. }
  806. // ===== Replication =====
  807. message ReplicationEntry {
  808. uint64 sequence = 1;
  809. uint64 global_timestamp = 2;
  810. string node_id = 3;
  811. OperationType op = 4;
  812. string collection = 5;
  813. string document_id = 6;
  814. uint64 document_version = 7;
  815. bytes data = 8;
  816. }
  817. enum OperationType {
  818. OP_UNKNOWN = 0;
  819. OP_INSERT = 1;
  820. OP_UPDATE = 2;
  821. OP_DELETE = 3;
  822. OP_UPSERT = 4;
  823. OP_CREATE_COLLECTION = 5;
  824. OP_DROP_COLLECTION = 6;
  825. }
  826. message ReplicationMessage {
  827. oneof content {
  828. ReplicationEntry entry = 1;
  829. Heartbeat heartbeat = 2;
  830. WatermarkUpdate watermark = 3;
  831. SyncRequest sync_request = 4;
  832. }
  833. }
  834. message Heartbeat {
  835. string node_id = 1;
  836. uint64 timestamp = 2;
  837. uint64 sequence = 3;
  838. }
  839. message WatermarkUpdate {
  840. string node_id = 1;
  841. uint64 sequence = 2;
  842. }
  843. message SyncRequest {
  844. uint64 from_sequence = 1;
  845. }
  846. message GetEntriesRequest {
  847. uint64 from_sequence = 1;
  848. uint32 limit = 2;
  849. }
  850. message GetNodeStateRequest {
  851. }
  852. message NodeState {
  853. string node_id = 1;
  854. uint64 current_sequence = 2;
  855. map<string, uint64> peer_watermarks = 3;
  856. uint64 document_count = 4;
  857. repeated string collections = 5;
  858. bool healthy = 6;
  859. // Per-collection sequence tracking for collection discovery
  860. map<string, uint64> collection_sequences = 7;
  861. }
  862. // ===== Health and Stats =====
  863. message HealthCheckRequest {
  864. }
  865. // v2.15.0 - capability negotiation.
  866. //
  867. // `capabilities` names features, not versions: a client gates a feature on its
  868. // NAME being present, so a patched or backported server reports exactly what it
  869. // can do. Names are stable forever and never reused; a feature that changes
  870. // meaning gets a new name. The list a server sends is in
  871. // service/src/server_capabilities.hpp.
  872. //
  873. // Clients send their own library version in the request metadata key
  874. // `sbdb-client-version` on every call, so a server can keep an old behaviour
  875. // for an old client if a meaning ever has to change. `client_version` echoes
  876. // what this call carried (empty if none).
  877. message GetServerInfoRequest {
  878. }
  879. // v2.17.0 - encryption at rest. A value must be stored encrypted when its
  880. // collection is `encrypted` (every value), when its path is in the collection's
  881. // `sensitive_fields` (or under one), or when its name matches a built-in
  882. // sensitive pattern (password, secret, token, api_key, apiKey, credentials) at
  883. // any depth.
  884. message VerifyEncryptionRequest {
  885. string collection = 1; // empty = every user collection
  886. }
  887. message EncryptionAudit {
  888. string collection = 1;
  889. bool collection_encrypted = 2;
  890. repeated string sensitive_fields = 3;
  891. uint64 rows = 4;
  892. uint64 encrypted_values = 5; // stored as ciphertext
  893. uint64 plaintext_required = 6; // plaintext where ciphertext is required (must be 0)
  894. uint64 double_encrypted = 7; // ciphertext of ciphertext (must be 0)
  895. uint64 undecryptable = 8; // ciphertext this key cannot open (must be 0)
  896. uint64 history_versions = 9;
  897. uint64 history_plaintext_required = 10;
  898. uint64 history_double_encrypted = 11;
  899. repeated string samples = 12; // "<id>: <path>" of plaintext findings, up to 5
  900. }
  901. message VerifyEncryptionResponse {
  902. bool encryption_enabled = 1;
  903. bool at_rest_sealed = 2; // the one-time migration ran and no reseal is pending
  904. repeated EncryptionAudit collections = 3;
  905. }
  906. message GetServerInfoResponse {
  907. string version = 1; // e.g. "2.15.0"
  908. string commit = 2; // short git commit, or "unknown"
  909. repeated string capabilities = 3;
  910. string client_version = 4;
  911. }
  912. message HealthCheckResponse {
  913. bool healthy = 1;
  914. uint64 uptime_seconds = 2;
  915. uint64 document_count = 3;
  916. uint64 memory_used_bytes = 4;
  917. uint64 wal_size_bytes = 5;
  918. repeated PeerHealth peers = 6;
  919. }
  920. message PeerHealth {
  921. string node_id = 1;
  922. bool connected = 2;
  923. uint64 latency_ms = 3;
  924. uint64 lag_entries = 4;
  925. }
  926. message GetStatsRequest {
  927. }
  928. message GetStatsResponse {
  929. uint64 total_documents = 1;
  930. uint64 total_collections = 2;
  931. uint64 memory_used_bytes = 3;
  932. uint64 wal_sequence = 4;
  933. uint64 wal_size_bytes = 5;
  934. uint64 snapshot_count = 6;
  935. uint64 last_snapshot_sequence = 7;
  936. uint64 insert_count = 8;
  937. uint64 update_count = 9;
  938. uint64 delete_count = 10;
  939. uint64 query_count = 11;
  940. // Memory eviction stats
  941. uint64 evicted_documents = 12; // Documents currently evicted to disk
  942. uint64 total_evictions = 13; // Total eviction operations performed
  943. uint64 recovery_count = 14; // Documents recovered from eviction
  944. // Memory configuration
  945. uint64 max_memory_bytes = 15; // Configured max memory limit
  946. uint32 eviction_threshold_percent = 16; // Start evicting at this % of max
  947. uint32 eviction_target_percent = 17; // Evict down to this % of max
  948. // Operation timing (microseconds) - for performance monitoring
  949. uint64 get_count = 18; // Number of get operations
  950. uint64 get_total_micros = 19; // Total time spent in get operations
  951. uint64 get_max_micros = 20; // Max single get operation time
  952. uint64 insert_total_micros = 21;
  953. uint64 insert_max_micros = 22;
  954. uint64 update_total_micros = 23;
  955. uint64 update_max_micros = 24;
  956. uint64 query_total_micros = 25;
  957. uint64 query_max_micros = 26;
  958. }
  959. // ===== View Operations =====
  960. message ViewDefinition {
  961. string name = 1; // view name (globally unique, cannot start with _)
  962. string collection = 2; // target real collection (must NOT be another view)
  963. repeated string include = 3; // field paths to include (dot-notation for nested)
  964. repeated string exclude = 4; // field paths to exclude (ignored if include is non-empty)
  965. repeated Filter where = 5; // baked-in filters (AND-merged with caller filters)
  966. Sort default_sort = 6; // baked-in default sort (used when caller doesn't specify)
  967. uint64 created_at = 7;
  968. uint64 updated_at = 8;
  969. }
  970. message CreateViewRequest {
  971. string name = 1;
  972. string collection = 2;
  973. repeated string include = 3;
  974. repeated string exclude = 4;
  975. repeated Filter where = 5;
  976. Sort default_sort = 6;
  977. }
  978. message CreateViewResponse {
  979. bool success = 1;
  980. string error = 2;
  981. }
  982. message DropViewRequest {
  983. string name = 1;
  984. }
  985. message DropViewResponse {
  986. bool success = 1;
  987. string error = 2;
  988. }
  989. message ListViewsRequest {
  990. // Restrict the listing to one project namespace. Empty lists every
  991. // project (operator/CLI use). Clients always set it so a workspace
  992. // never sees another workspace's views.
  993. string project = 1;
  994. }
  995. message ListViewsResponse {
  996. repeated ViewDefinition views = 1;
  997. }
  998. message GetViewInfoRequest {
  999. string name = 1;
  1000. }
  1001. message GetViewInfoResponse {
  1002. ViewDefinition view = 1;
  1003. bool found = 2;
  1004. }
  1005. // ===== Relation (Referential Integrity) Operations — v2.11.0 T6b =====
  1006. //
  1007. // A relation says: documents in `child` reference documents in `parent`
  1008. // through `child_field` (a dot-path that may resolve to a single id or an
  1009. // array of ids). Declarations are persisted in the global `_relations`
  1010. // system collection (mirrors `_views`) and are project-qualified like any
  1011. // other collection-carrying name. Management is admin-only.
  1012. message RelationDefinition {
  1013. string name = 1; // relation name, project-qualified
  1014. string child = 2; // collection holding the reference, project-qualified
  1015. string child_field = 3; // dot-path on the child; may resolve to an array of ids
  1016. string parent = 4; // collection being referenced, project-qualified
  1017. // "restrict" (default) | "cascade" | "set_null" | "no_action".
  1018. //
  1019. // ALL FOUR ARE ENFORCED as of v2.11.0, and an unrecognised value is
  1020. // REFUSED by CreateRelation rather than coerced to "restrict".
  1021. // restrict - the parent delete fails FAILED_PRECONDITION while any
  1022. // child still references it.
  1023. // cascade - DESTRUCTIVE: children referencing the parent are deleted
  1024. // atomically with it. If child_field resolves to an ARRAY,
  1025. // the parent id is pulled from the array and the child is
  1026. // KEPT (cascade and set_null collapse there). Refused if a
  1027. // child is itself protected by its own restrict relation.
  1028. // Not recursive.
  1029. // set_null - DESTRUCTIVE: the child's reference field is set to null
  1030. // and the child is kept. Arrays behave as under cascade.
  1031. // no_action - the delete proceeds, the reference is left dangling.
  1032. string on_delete = 5;
  1033. // ENFORCED as of v2.11.0: a write to the child naming a parent that does
  1034. // not exist is rejected with FAILED_PRECONDITION. An empty-string
  1035. // reference is a hard rejection.
  1036. bool validate_on_write = 6;
  1037. uint64 created_at = 7;
  1038. uint64 updated_at = 8;
  1039. }
  1040. message CreateRelationRequest {
  1041. string name = 1;
  1042. string child = 2;
  1043. string child_field = 3;
  1044. string parent = 4;
  1045. string on_delete = 5; // empty defaults to "restrict"
  1046. bool validate_on_write = 6;
  1047. }
  1048. message CreateRelationResponse {
  1049. bool success = 1;
  1050. string error = 2;
  1051. // v2.11.0 T7 — rows indexed by the bootstrap scan. Declaring a relation
  1052. // over a collection that already has rows backfills the reverse index
  1053. // immediately (mirrors CreateIndexResponse.rows_indexed), so enforcement
  1054. // covers pre-existing children from the moment the relation is declared,
  1055. // not only writes made afterwards.
  1056. uint64 rows_indexed = 3;
  1057. }
  1058. message DropRelationRequest {
  1059. string name = 1;
  1060. }
  1061. message DropRelationResponse {
  1062. bool success = 1;
  1063. string error = 2;
  1064. }
  1065. message ListRelationsRequest {
  1066. // Restrict the listing to one project namespace. Empty lists every
  1067. // project (operator/CLI use). Clients always send their own project so
  1068. // one workspace never enumerates another's relations.
  1069. string project = 1;
  1070. }
  1071. message ListRelationsResponse {
  1072. repeated RelationDefinition relations = 1;
  1073. }
  1074. message GetRelationInfoRequest {
  1075. string name = 1;
  1076. }
  1077. message GetRelationInfoResponse {
  1078. RelationDefinition relation = 1;
  1079. bool found = 2;
  1080. }
  1081. // v2.11.0 T5 — "what would happen if I deleted this?", answered without
  1082. // deleting anything. A relational database exposes its constraints through
  1083. // DDL you can read; a document store has none, so this has to be a query.
  1084. // Gated as an ordinary READ on `collection` (it changes nothing), unlike
  1085. // the relation-management RPCs above which are admin-only.
  1086. message DescribeDeleteRequest {
  1087. string collection = 1;
  1088. string id = 2;
  1089. }
  1090. message RelationImpact {
  1091. string relation = 1;
  1092. string child_collection = 2;
  1093. string child_field = 3;
  1094. string on_delete = 4; // restrict | cascade | set_null | no_action
  1095. uint64 child_count = 5;
  1096. repeated string sample_child_ids = 6; // at most five
  1097. bool blocks = 7;
  1098. }
  1099. message DescribeDeleteResponse {
  1100. bool success = 1;
  1101. string error = 2;
  1102. bool would_be_blocked = 3;
  1103. repeated RelationImpact impacts = 4;
  1104. }
  1105. // v2.11.0 T7 — the bootstrap-scan gap. Declaring a relation with T3 alone
  1106. // only maintains the reverse index going FORWARD from writes made after
  1107. // declaration; rows already in the child collection were never indexed, so
  1108. // enforcement silently missed them. This RPC answers "is that still true
  1109. // right now, for this relation" without changing anything.
  1110. message CheckRelationRequest {
  1111. string name = 1; // relation name, project-qualified like the others
  1112. }
  1113. // One parent id referenced by the child collection's data, whose parent
  1114. // document does not exist.
  1115. message DanglingReference {
  1116. string parent_id = 1;
  1117. uint64 child_count = 2; // children of this parent, from the index
  1118. repeated string sample_child_ids = 3; // at most five
  1119. }
  1120. message CheckRelationResponse {
  1121. bool success = 1;
  1122. string error = 2;
  1123. // Every dangling parent id found, not just the reported sample - so a
  1124. // capped `dangling` list below does not silently understate the problem.
  1125. uint64 total_dangling = 3;
  1126. // Capped (see the server implementation) so a badly out-of-sync relation
  1127. // cannot blow up the response size; total_dangling is the true count.
  1128. repeated DanglingReference dangling = 4;
  1129. }
  1130. // ===== Collection Configuration =====
  1131. // Per-collection configuration for timestamp precision and other runtime knobs.
  1132. // Stored in the _collection_meta system collection.
  1133. message CollectionConfig {
  1134. // "ms" (default) — _created_at/_updated_at stamped in milliseconds since epoch
  1135. // "ns" — _created_at/_updated_at stamped in nanoseconds since epoch
  1136. // Empty on a ConfigureCollection request means "leave unchanged".
  1137. string timestamp_precision = 1;
  1138. // v2.4.5 — version history on/off for an EXISTING collection.
  1139. //
  1140. // `optional` (proto3 field presence) is load-bearing, not decoration: a
  1141. // plain bool defaults to false, so any ConfigureCollection call that meant
  1142. // to set only timestamp_precision would silently switch versioning OFF.
  1143. // With presence, an absent field means "leave unchanged" and the server
  1144. // overlays only what the caller actually set.
  1145. //
  1146. // Disabling stops NEW versions being recorded; history already on disk
  1147. // stays readable, so this is reversible. Distinct from max_versions=0,
  1148. // which means "unlimited", not "off".
  1149. optional bool versioning_enabled = 2;
  1150. // v2.11.0 T8 — whether declared relations are enforced for this collection.
  1151. //
  1152. // `optional` for the same reason versioning_enabled is: a plain bool
  1153. // defaults to false, so a ConfigureCollection call that meant to set
  1154. // only timestamp_precision would silently switch relation enforcement
  1155. // OFF. With presence, an absent field means "leave unchanged".
  1156. //
  1157. // Defaults to true (enforced) when never explicitly configured -
  1158. // declaring a relation names its child and parent explicitly, so the
  1159. // declaration IS the opt-in.
  1160. optional bool relations_enforced = 3;
  1161. // Room for future per-collection knobs
  1162. }
  1163. message ConfigureCollectionRequest {
  1164. string collection = 1;
  1165. CollectionConfig config = 2;
  1166. }
  1167. message ConfigureCollectionResponse {
  1168. bool success = 1;
  1169. string error = 2;
  1170. }
  1171. // v2.9.0 — secondary index management.
  1172. // ===== Collection schema (v2.16.0) =====
  1173. //
  1174. // The schema language is a JSON Schema subset; any keyword outside it is
  1175. // refused (INVALID_ARGUMENT, reason `invalid_schema`) so a schema never looks
  1176. // stricter than what is enforced. See service/src/schema/json_schema.hpp.
  1177. // A refused WRITE answers INVALID_ARGUMENT, reason `schema_violation`, with the
  1178. // violating fields in the detail's `fields`.
  1179. message SetCollectionSchemaRequest {
  1180. string collection = 1;
  1181. string schema_json = 2; // empty = remove the collection's schema
  1182. string mode = 3; // "enforce" (default) or "audit"
  1183. }
  1184. // One existing row that does not conform.
  1185. message SchemaRowViolation {
  1186. string id = 1;
  1187. string message = 2;
  1188. repeated string fields = 3;
  1189. }
  1190. message SetCollectionSchemaResponse {
  1191. // false = not applied: `error` says why. In enforce mode a schema that any
  1192. // existing row violates is refused, with up to 10 `examples`; in audit
  1193. // mode it is applied and the same counts are reported.
  1194. bool success = 1;
  1195. string error = 2;
  1196. uint64 rows_checked = 3;
  1197. uint64 violating_rows = 4;
  1198. repeated SchemaRowViolation examples = 5;
  1199. }
  1200. message GetCollectionSchemaRequest {
  1201. string collection = 1;
  1202. }
  1203. message GetCollectionSchemaResponse {
  1204. bool has_schema = 1;
  1205. string schema_json = 2; // as it was set
  1206. string mode = 3; // "enforce" | "audit"
  1207. uint64 audit_violations = 4; // audit mode: non-conforming writes let through, since the schema was armed
  1208. uint64 refusals = 5; // enforce mode: writes refused, since the schema was armed
  1209. bool armed = 6; // false only if the stored schema no longer compiles (logged at boot)
  1210. }
  1211. message SuggestCollectionSchemaRequest {
  1212. string collection = 1;
  1213. uint64 sample_limit = 2; // 0 = every row
  1214. }
  1215. message SuggestCollectionSchemaResponse {
  1216. // A schema every scanned row conforms to: see SchemaSuggester in
  1217. // service/src/schema/json_schema.hpp for what it infers and what it
  1218. // deliberately only reports.
  1219. string schema_json = 1;
  1220. uint64 rows_scanned = 2;
  1221. bool complete = 3; // every row was scanned (no sample_limit cut)
  1222. }
  1223. message CreateIndexRequest {
  1224. // Project-qualified collection name, as every other collection-carrying
  1225. // request takes.
  1226. string collection = 1;
  1227. // Field to index. Dotted paths address nested fields ("nest.deep"), and the
  1228. // document metadata fields (_id, _created_at, _updated_at, _version) are
  1229. // addressable too.
  1230. string field = 2;
  1231. // v2.11.0 T11 — when true, the field carries a UNIQUE constraint: two
  1232. // documents may never hold the same value for it. Declaring this over a
  1233. // collection that already contains duplicate values is REFUSED (see
  1234. // CreateIndexResponse.duplicate_examples) rather than accepted and left
  1235. // silently unenforced against the data that already violates it.
  1236. //
  1237. // v2.12.0 - NULL IS NOT A VALUE for uniqueness: any number of documents
  1238. // may hold null (or omit the field), as in SQL. Before 2.12.0 two nulls
  1239. // collided while two absent fields did not.
  1240. bool unique = 3;
  1241. // v2.12.0 - a COMPOSITE unique constraint over the TUPLE of these fields
  1242. // (two or more; `field` must then be empty and `unique` true). Two
  1243. // documents may not hold the same combination. A document in which any
  1244. // of the fields is absent, null, an object or an array is not constrained
  1245. // - the SQL rule for a NULL in a unique key. Composite constraints back no
  1246. // query (the planner never uses them) and are listed by ListIndexes with
  1247. // `fields` set. Declaring one over existing duplicates is refused with
  1248. // examples, as for a single field.
  1249. repeated string fields = 4;
  1250. }
  1251. message CreateIndexResponse {
  1252. bool success = 1;
  1253. string error = 2;
  1254. // Rows indexed by the backfill. Creating an index over an existing
  1255. // collection populates it, so it is usable immediately rather than only for
  1256. // rows written afterwards.
  1257. uint64 rows_indexed = 3;
  1258. // True when the index already existed - creation is idempotent.
  1259. bool already_existed = 4;
  1260. // v2.11.0 T11 — set when a `unique=true` request was refused because the
  1261. // field already holds duplicate values. `error` explains the refusal;
  1262. // these are up to five example document ids that collide, one entry per
  1263. // colliding value, so the caller can go fix the data rather than guess.
  1264. repeated string duplicate_examples = 5;
  1265. }
  1266. message DropIndexRequest {
  1267. string collection = 1;
  1268. string field = 2;
  1269. // v2.12.0 - drop the composite unique constraint over exactly these
  1270. // fields, in the order they were declared. `field` must then be empty.
  1271. repeated string fields = 3;
  1272. }
  1273. message DropIndexResponse {
  1274. bool success = 1;
  1275. string error = 2;
  1276. }
  1277. message ListIndexesRequest {
  1278. string collection = 1;
  1279. }
  1280. message IndexInfo {
  1281. string field = 1;
  1282. // Distinct values held, and total postings. Both come from the index itself
  1283. // rather than a scan, so an operator can judge selectivity - a field whose
  1284. // postings are concentrated in few values will not be used by the planner.
  1285. uint64 distinct_values = 2;
  1286. uint64 entries = 3;
  1287. // v2.11.0 T11 — true when this index also carries a UNIQUE constraint.
  1288. bool unique = 4;
  1289. // v2.12.0 - set for a COMPOSITE unique constraint: its fields, in order.
  1290. // `field` then holds a display form ("a+b") and `unique` is true.
  1291. repeated string fields = 5;
  1292. }
  1293. message ListIndexesResponse {
  1294. bool success = 1;
  1295. string error = 2;
  1296. repeated IndexInfo indexes = 3;
  1297. }
  1298. message GetIndexValuesRequest {
  1299. string collection = 1;
  1300. string field = 2;
  1301. // Bounded on purpose: reading the values costs one document read each.
  1302. uint32 limit = 3;
  1303. // false walks from the highest value down, so limit=1 gives the maximum.
  1304. bool ascending = 4;
  1305. }
  1306. message IndexValueCount {
  1307. // The value as stored, JSON-encoded.
  1308. string value = 1;
  1309. uint64 count = 2;
  1310. }
  1311. message GetIndexValuesResponse {
  1312. bool success = 1;
  1313. string error = 2;
  1314. repeated IndexValueCount values = 3;
  1315. }
  1316. message GetCollectionConfigRequest {
  1317. string collection = 1;
  1318. }
  1319. message GetCollectionConfigResponse {
  1320. CollectionConfig config = 1;
  1321. bool found = 2;
  1322. }
  1323. message MigrateCollectionTimestampsRequest {
  1324. string collection = 1;
  1325. string from_precision = 2; // "ms" or "ns"
  1326. string to_precision = 3; // "ms" or "ns"
  1327. }
  1328. message MigrateCollectionTimestampsResponse {
  1329. bool success = 1;
  1330. string error = 2;
  1331. uint64 rows_migrated = 3; // how many documents had their timestamps updated
  1332. uint64 rows_skipped = 4; // already in target range (idempotent resume)
  1333. }
  1334. // ===== Read-Only Control =====
  1335. message SetReadOnlyRequest {
  1336. bool read_only = 1;
  1337. }
  1338. message SetReadOnlyResponse {
  1339. bool success = 1;
  1340. bool was_read_only = 2; // previous state
  1341. string error = 3;
  1342. }
  1343. message GetReadOnlyStatusRequest {}
  1344. message GetReadOnlyStatusResponse {
  1345. bool read_only = 1;
  1346. string reason = 2;
  1347. // Recovery outcome details (populated when auto-readonly triggered)
  1348. string recovery_outcome = 3; // "trivial_success" | "fresh_install" | "snapshot_fell_back" | "wal_only_replay" | "forced_empty" | "failed"
  1349. string expected_snapshot = 4;
  1350. string snapshot_used = 5;
  1351. string failure_reason = 6;
  1352. uint64 wal_entries_replayed = 7;
  1353. uint32 snapshots_attempted = 8;
  1354. }
  1355. // ===== Memory Stats =====
  1356. // Added in v1.7.0. Wire-compatible — server-side implementation lands in T9.
  1357. message GetMemoryStatsRequest {}
  1358. message CollectionMemoryStats {
  1359. string collection = 1;
  1360. uint64 document_count = 2;
  1361. uint64 estimated_bytes = 3;
  1362. uint64 evicted_stub_count = 4;
  1363. MemoryPriority priority = 5;
  1364. }
  1365. message GetMemoryStatsResponse {
  1366. uint64 total_memory_bytes = 1;
  1367. uint64 max_memory_bytes = 2;
  1368. uint32 pressure_percent = 3; // current usage / max × 100
  1369. string pressure_level = 4; // "normal" | "soft" | "hard" | "emergency"
  1370. repeated CollectionMemoryStats collections = 5;
  1371. // Most recent eviction
  1372. uint64 last_eviction_timestamp = 6; // ms since epoch, 0 if none
  1373. uint64 last_eviction_docs = 7;
  1374. uint64 last_eviction_bytes_freed = 8;
  1375. // v2.11.0 — TTL expiries a relation is refusing.
  1376. //
  1377. // ttl_blocked_documents is a GAUGE: how many documents are past their TTL
  1378. // right now and NOT being expired because deleting them would break a
  1379. // `restrict` relation (or because the cascade path is refusing while the
  1380. // LMDB mirror is unhealthy/drifted). It falls when a block lifts. Nonzero
  1381. // means those documents are outliving their retention policy - the
  1382. // deliberate alternative to silently orphaning their children.
  1383. //
  1384. // ttl_expiry_blocked_events is a monotonic COUNTER of refusal events, so it
  1385. // keeps rising while a block persists (each blocked document is retried on a
  1386. // slow cadence). Use the gauge for "how bad is it now", the counter for
  1387. // "is this still happening".
  1388. //
  1389. // Both are zero on any install that declares no relations.
  1390. uint64 ttl_blocked_documents = 9;
  1391. uint64 ttl_expiry_blocked_events = 10;
  1392. }