database.proto 56 KB

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